import React, {
  FC,
  MutableRefObject,
  memo,
  useEffect,
  useRef,
  useState,
  useCallback,
  Fragment,
} from "react";
import {
  message,
  Dropdown,
  Icon,
  Menu,
  Button,
  Tooltip,
  Avatar,
  Modal,
  Switch,
  Input,
  Popconfirm,
  Checkbox,
} from "antd";
import { Link } from "react-router-dom";
import { usePersistFn } from "ahooks";
import { getImageUrl, timeAgo } from "educoder";
import "./style.module.less";
import { useAcr, useNote, useGlobal, usePr } from "../../model";
const AnnotationStatus = {
  Init: 'Init',
  Ignore: 'Ignore',
  Confirm: 'Confirm',
  FalsePositive: 'FalsePositive',
}
const noteType = {
  comment: 'comment',
  problem: 'problem',
}

export const Commenting = (props) => {
  const { user } = useGlobal();
  const { addComment } = useNote();
  const { toVersion, stDiff } = useAcr();
  const submit = usePersistFn(async (note, type) => {
    try {
      console.log(note, type);
      await addComment({
        note,
        diffId: toVersion.id,
        line_code: props.lineCode,
        parent_id: props.id,
        path: props.path,
        type: type || 'comment',
        diff: props.id ? null : stDiff,
      });
      props.onClose && props.onClose();
    } catch (e) {
      console.error(e);
    }
  });

  const { replyNote } = props;

  const [note, setNote] = useState("");
  const [isProblem, setIsProblem] = useState(false);

  const onSubmit = useCallback(() => {
    const submitNote = replyNote ? insertReplyNote(note, replyNote) : note;
    submit(submitNote, isProblem ? noteType.problem : noteType.comment);
  }, [note, replyNote, isProblem]);

  function insertReplyNote(baseNote, replyNote) {
    if (replyNote && replyNote.note) {
      const replyLine = replyNote.note.split("\n");
      const blockquoteNote = [
        `<!-- reply id="${replyNote.id}" -->`,
        ...replyLine,
      ]
        .map((note) => `> ${note}`)
        .join("\n");
      return blockquoteNote + "\n\n" + baseNote;
    } else {
      return baseNote;
    }
  }

  return (
    // <div className="arc-container">
    <div
      className={`arc-commenting-container ${props.noPadding ? "no-padding" : ""}`}>
      <div className="avatar">
        <Tooltip title={user.name}>
          <Avatar src={user && user.image_url
            ? getImageUrl(`/${user.image_url}`)
            : "images/avatars/User/b"} size={24} />
        </Tooltip>
      </div>
      <Input.TextArea
        autoFocus
        placeholder="请输入评论信息"
        value={note}
        onChange={(e) => setNote(e.target.value)}
        style={{ height: 150 }}
      />
      <div className="action">
        <div>
          <Button
            type="primary"
            onClick={onSubmit}
            disabled={!note.trim()}
            style={{ marginRight: 8 }}
          >
            评论
          </Button>
          {note.trim() ? (
            <Popconfirm
              title="你确定要取消？"
              okText="确定"
              cancelText="取消"
              onConfirm={props.onClose}
            >
              <Button>取消</Button>
            </Popconfirm>
          ) : (
            <Button onClick={props.onClose}>取消</Button>
          )}
        </div>
        <div>
          {replyNote && (
            <div className="reply-note">Reply to {replyNote.author.name}</div>
          )}
        </div>
      </div>
    </div>
    // </div>
  );
};

const ReplyItem = memo(({ note, isChild }) => {
  const { user } = useGlobal();
  const { deleteComment } = useNote();
  const [visible, setVisible] = useState(false);

  return <div className={`reply-item ${isChild ? 'reply-item-child' : ''}`}>
    <div className="reply-item-head">
      <Link
        to={`/${note.user && note.user.login}`}
        className="show-user-link"
      >
        <Avatar src={note.user && note.user.imageUrl
          ? getImageUrl(`/${note.user.imageUrl}`)
          : "images/avatars/User/b"} size={24} />
      </Link>
      <Link
        to={`/${note.user && note.user.login}`}
        className="show-user-link color-black ml10 fwb"
      >
        {note.user && note.user.username}
      </Link> 于 <span className="show-user-link color-black">{timeAgo(note.createdAt)}</span> 发表评论：
      <span className="btn-right">
        {user &&
          (user.admin ||
            user.login === note.user.login) ? (
          <Popconfirm
            placement="bottom"
            title={"确定要删除当前评论吗?"}
            okText="是"
            cancelText="否"
            onConfirm={() => deleteComment(note.id)}
          >
            <Button type="link">
              <i className="iconfont icon-shanchu3 font-15 color-grey-6 mr5 ver-middle"></i>
              <span className="font-12 color-grey-6">删除</span>
            </Button>
          </Popconfirm>
        ) : (
          ""
        )}
        {!isChild ? <Button
          type="link"
          className="ml-10"
          onClick={() => setVisible(true)}
        >
          <i className="iconfont icon-huifu1 font-15 color-grey-6 mr5 ver-middle"></i>
          <span className="font-12 color-grey-6">回复</span>
        </Button> : ''}
      </span>
    </div>

    <div className="reply-item-content">{note.note}</div>
    {visible && <Commenting style={{ paddingLeft: '20px' }} onClose={() => { setVisible(false) }} {...note} />}
  </div>
})

export const DiscussionItem = memo((props) => {
  const { noteId } = props;
  const { commentPack, deleteComment } = useNote();

  // const [commenting, setCommenting] = useState(false);
  // const [commentReply, setCommentReply] = useState();

  const replyIdSet = commentPack.noteIdToReplyIdSet.get(noteId);
  const replyIds = replyIdSet
    ? Array.from(replyIdSet).sort((a, b) => a - b)
    : null;

  // const pending = (function () {
  //   if (!commentPack.hasPendingReview) {
  //     return false;
  //   }
  //   const reviewId = commentPack.noteIdToReviewId.get(noteId);
  //   if (!reviewId) return false;
  //   const review = reviewId ? commentPack.reviewIdToReview.get(reviewId) : null;
  //   if (!review) return false;
  //   return review.pending;
  // })();
  // const hasPendingNote = (function () {
  //   if (pending) return true;
  //   if (replyIds) {
  //     for (const replyId of replyIds) {
  //       const reviewId = commentPack.noteIdToReviewId.get(replyId);
  //       if (reviewId && commentPack.reviewIdToReview.get(reviewId) && commentPack.reviewIdToReview.get(reviewId).pending) {
  //         return true;
  //       }
  //     }
  //   }
  //   return false;
  // })();

  // const handleReply = (replyNote) => {
  //   if (replyNote) {
  //     setCommentReply(replyNote);
  //   }
  //   setCommenting(true);
  // };

  // useEffect(() => {
  //   if (!commenting) {
  //     setCommentReply(undefined);
  //   }
  // }, [commenting]);


  const note = commentPack.noteIdToNote.get(noteId);
  if (!note) return null;

  // console.log('note');
  // console.log(note);
  return (
    <div className="arc-container">
      {/* <div>
        {note.type === noteType.problem && (
          <Fragment>
            {note.state === "resolved" && !pending && "已解决"}
            {note.state === "opened" && !pending && "待解决"}
            {pending && "需要回应"}
          </Fragment>
        )}
      </div> */}
      <ReplyItem note={note} />

      {replyIds && (
        <div style={{ paddingLeft: 50 }}>
          {replyIds.reverse().map((replyId) => {
            const note = commentPack.noteIdToNote.get(replyId);
            if (!note) return null;
            return <ReplyItem note={note} key={replyId} isChild={true} />
          })}
        </div>
      )}
    </div>
  );
});

export const Menubar = memo((props) => {
  const {projectsId,owner,mergeId}=props;
  const [isFullscreen, setFullscreen] = React.useState(
    props.initialFullscreen || false
  );
  const handleChangeFullscreen = (isFullscreen) => {
    setFullscreen(isFullscreen);
    if (isFullscreen) {
      message.info("全屏模式支持直接使用 ↑/↓ 切换变更文件");
    }
    props.handleFullscreenChange(isFullscreen);
    props.logFullScreen(isFullscreen);
  };
  useEffect(() => {
    if (isFullscreen) {
      document.body.style.overflow = "hidden";
    }
    return () => {
      document.body.style.overflow = "";
    };
  }, [isFullscreen]);

  const { versions, fromVersion, toVersion, updateQuery } = useAcr();

  const idToVerbose = new Map();
  idToVerbose.set(0, "Base Version");


  versions.forEach((version, index) => {
    if (index === versions.length - 1) {
      idToVerbose.set(version.id, `Latest Version`);
    } else {
      idToVerbose.set(version.id, `Version ${versions.length - index - 1}`);
    }
  });
  
  const fromId = fromVersion && fromVersion.id || 0;
  const toId = toVersion && toVersion.id || 0;

  const filterCleared = fromId === 0 && toId === versions[0] && versions[0].id;

  function renderMenuItem(version, selectedId) {
    const verbose = idToVerbose.get(version.id);
    return (
      <Menu.Item
        className={`arc-menuItem ${version.id === selectedId ? "selected" : ""
          }`}
        key={version.id}
      >
        <div className='headRow'>
          <span>{verbose}</span>
          <span>{version.headCommitSha.slice(0, 8)}</span>
        </div>
        <div className='desc'>
          包含 {version.commitsCount}次提交，{version.filesCount} 份文件变更
        </div>
      </Menu.Item>
    );
  }

  const menuFrom = (
    <Menu
      onClick={(e) => {
        const val = parseInt(e.key);
        updateQuery({
          from: val === 0 ? undefined : val,
        });
      }}
    >
      {versions.slice(1).map((version) => renderMenuItem(version, fromId))}
      <Menu.Item
        key={0}
        className={`${'menuItem'} ${fromId === 0 ? 'selected' : ""}`}
      >
        Base Version
      </Menu.Item>
    </Menu>
  );

  const menuTo = (
    <Menu
      onClick={(e) => {
        updateQuery({
          to: parseInt(e.key),
        });
      }}
    >
      {versions
        .slice(0, versions.length)
        .map((version) => renderMenuItem(version, toId))}
    </Menu>
  );

  const MenuStyle = {
    zIndex: 1200,
  };

  return (
    <div className="arc-menubar">
      <div className={'group'}>
        {versions.length !== 0 && (
          <div className='versionContainer'>
            <Link to={`/${owner}/${projectsId}/pulls/${mergeId}`} className="font-14 color-grey-9">返回</Link>
            <Dropdown overlay={menuFrom} trigger={["click"]} overlayStyle={MenuStyle}>
              <div className='versionItem'>
                <span>{idToVerbose.get(fromId)}</span>
                <Icon type="down" />
              </div>
            </Dropdown>
            <div>
              <Icon type="arrow-right" />
            </div>
            <Dropdown overlay={menuTo} trigger={["click"]} overlayStyle={MenuStyle}>
              <div className={'versionItem'}>
                <span>{idToVerbose.get(toId)}</span>
                <Icon type="down" />
              </div>
            </Dropdown>

            {!filterCleared && (
              <div>
                <a
                  onClick={() => {
                    updateQuery({
                      from: undefined,
                      to: undefined,
                    });
                  }}
                >
                  重置
                </a>
              </div>
            )}
          </div>
        )}
      </div>
      <div className={'group'}>
        {/* {isFullscreen ? null : (
          <div className={'switchContainer'}>
            <span className={'ideLabel'}>IDE 模式</span>
            <Tooltip
              placement="top"
              title="提供 IDE 代码浏览体验、完善的语言服务和高效的代码编辑"
            >
              <Switch checked onChange={props.toggleViewerType} />
            </Tooltip>
          </div>
        )} */}
        {isFullscreen ? (
          <Icon
            type="fullscreen-exit"
            onClick={() => handleChangeFullscreen(false)}
          />
        ) : (
          <Tooltip title="全屏">
            <Icon
              type="fullscreen"
              onClick={() => handleChangeFullscreen(true)}
            />
          </Tooltip>
        )}
      </div>
    </div>
  );
});

export const AnnotationEntry = memo((props) => {
  const { annotation, checkSuite } = props;

  // 定位
  const anchorOffsetRef = useRef(null);
  const hash = `#annotation_${annotation.id}`;
  const hashActive = hash === window.location.hash;
  useEffect(() => {
    setTimeout(() => {
      if (hashActive) {
        anchorOffsetRef.current && anchorOffsetRef.current.scrollIntoView(true);
      }
    }, 500);
  });

  const [isIgnore, setIsIgnore] = useState(
    annotation.feedBackStatus === AnnotationStatus.Ignore
  );

  return (
    <div className="arc-container">
      <div
        ref={anchorOffsetRef}
        id={`annotation_${annotation.id}`}
        className="arc-annotationContainer"
      >
        <div className={'codeLine'}>
          <div>{annotation.level}</div>
          <div className={'line'}>
            {annotation.startLine === annotation.endLine ? (
              <span>
                对{annotation.endLine}
                行代码分析
              </span>
            ) : (
              <span>
                对{annotation.startLine}到{annotation.endLine}
                行代码分析
              </span>
            )}
          </div>
        </div>
        <div className={'botRow'}>
          <Avatar
            alt={checkSuite.service.nameShow}
            size={20}
            src="https://gw-office.alipayobjects.com/bmw-prod/a9596840-928c-4603-a865-b24373ab4b4d.png"
          />
          <div>
            <div className={'strong'}>{checkSuite.service.nameShow}</div>
          </div>
        </div>
        <div className={'content'}>
          <p>{annotation.title}</p>
          <div>{annotation.message}</div>
        </div>
        <div className={'detail'}>
          <div>
            {annotation.bugId ? (
              isIgnore ? (
                <Button type="primary" style={{ marginRight: 8 }}>
                  取消忽略
                </Button>
              ) : (
                <Fragment>
                  <Button style={{ marginRight: 8 }}>忽略</Button>
                  <Button style={{ marginRight: 8 }}>误报</Button>
                  <Button>确认</Button>
                </Fragment>
              )
            ) : null}
          </div>
          <div>
            <a
              className={'halfPlainA'}
              href={`https://codeinsightapi.alipay.com/api/v1/describe?bug_type=${annotation.bugType}&bug_id=${annotation.bugId}`}
              target="_blank"
            >
              查看问题详情 <Icon type="double-right" />
            </a>
          </div>
        </div>
      </div>
    </div>
  );
});

export const PRMoreActionLinks = ({
  setVisible,
}) => {
  const { pr } = usePr();
  const { project } = useGlobal();
  const [checkoutBranchVisible, setCheckoutBranchVisible] = useState(false);

  return (
    <Fragment>
      <div>正在丰富功能中...</div>
      <div style={{display:'none'}}>
        <Switch checked />
      </div>
      {/* <div
        className="arc-checkoutBranch"
        onClick={() => {
          setCheckoutBranchVisible(true);
          setVisible(false);
        }}
      >
        检出分支
      </div>
      <a
        className="arc-flexA"
        download
        href={`http://code.test.alipay.net/${project.pathWithNamespace}/pull_requests/${pr.iid}.patch`}
      >
        <span onClick={() => setVisible(false)}>下载 patch 文件</span>
      </a>
      <a
        className="arc-flexA"
        download
        href={`http://code.test.alipay.net/${project.pathWithNamespace}/pull_requests/${pr.iid}.diff`}
      >
        <span onClick={() => setVisible(false)}>下载 diff 文件</span>
      </a>
      <Modal
        title="检出，评审，并在本地执行合并"
        visible={checkoutBranchVisible}
        footer={null}
        onCancel={() => setCheckoutBranchVisible(false)}
      >
        <div className="arc-checkout">
          <p>
            <span className="fw">Step 1.</span> Fetch and check out the branch
            for this pull request
          </p>
          <pre>
            git fetch origin
            <br />
            {`git checkout -b ${pr.sourceBranch} origin/${pr.sourceBranch}`}
          </pre>
          <p>
            <span className="fw">Step 2.</span> Review the changes locally
          </p>
          <p>
            <span className="fw">Step 3.</span> Merge the branch and fix any
            conflicts that come up
          </p>
          <pre>
            git fetch origin
            <br />
            {`git checkout origin/${pr.targetBranch}`}
            <br />
            git merge --no-ff master
          </pre>
          <p>
            <span className="fw">Step 4.</span> Push the result of the merge
          </p>
          <pre>{`git push origin ${pr.targetBranch}`}</pre>
        </div>
      </Modal> */}
    </Fragment>
  );
};
