import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { MrContext } from '../activityBarView/context';
import { getMergeRequestTreeItemDescription } from '../common/mergeStatus';
import { CodingMergeRequestState, MergeRequestState } from '../common/types';
import { GitCompareIcon, RepoIcon } from '../components/icon';

export const AddCommentSimple: React.FC<MergeRequestState> = mrState => {
	const {
		approve,
		close,
		refresh,
		updateMR,
		mergeBranch,
		openMergeEditor,
		checkLocalMergeStatus,
		getLocalConflictFileList,
		mergeCommitAndPush,
		exitReviewMode,
	} = useContext(MrContext);
	const [isBusy, setBusy] = useState(false);
	const [isMerging, setIsMerging] = useState(false);
	const [conflictFileList, setConflictFileList] = useState<string[]>();

	// mr 关闭或异常
	const disabled = [
		CodingMergeRequestState.ACCEPTED,
		CodingMergeRequestState.CANNOTMERGE,
		CodingMergeRequestState.REFUSED,
		CodingMergeRequestState.ABNORMAL,
	].includes(mrState.status);

	const onChangeTextarea = (e: React.ChangeEvent<HTMLTextAreaElement>): void => {
		updateMR({ pendingCommentText: e.target.value });
	};

	const approveHandler = useCallback(async () => {
		try {
			setBusy(true);
			await approve(mrState.pendingCommentText);
			updateMR({ pendingCommentText: '', status: CodingMergeRequestState.ACCEPTED });
		} finally {
			setBusy(false);
		}
	}, [approve, mrState, setBusy]);

	const closeHandler = useCallback(async () => {
		try {
			setBusy(true);
			await close();
			updateMR({ pendingCommentText: '', status: CodingMergeRequestState.REFUSED, conflicts: [] });
		} finally {
			setBusy(false);
		}
	}, [close, setBusy]);

	const handleClickConflictFile = (isResolve, item) => {
		console.log(isMerging, isResolve, item);
		isMerging && !isResolve && openMergeEditor(item);
	};

	useEffect(() => {
		checkLocalMergeStatus().then(async res => {
			if (res === true) {
				setIsMerging(true);
				const conflictFileList = await getLocalConflictFileList();
				setConflictFileList(conflictFileList);
			}
		});
	}, []);

	return (
		<div className="comment-body">
			{disabled && (
				<div style={{ color: '#e9a700', marginBottom: '20px' }}>
					{getMergeRequestTreeItemDescription(mrState)}
				</div>
			)}

			{mrState.status !== CodingMergeRequestState.ACCEPTED && mrState.conflicts.length > 0 && (
				<div style={{ display: 'flex', flexDirection: 'column', marginBottom: '10px' }}>
					<p>当前 mr 存在冲突</p>
					<p>冲突文件({isMerging ? conflictFileList?.length : mrState.conflicts.length})：</p>
					<ul>
						{mrState.conflicts.map(item => {
							const isResolve = conflictFileList?.includes(item) === false;
							return (
								<li onClick={() => handleClickConflictFile(isResolve, item)} key={item} style={{cursor: 'pointer'}}>
									{isResolve ? `✅ ${item}` : `❗ ${item}`}
								</li>
							);
						})}
					</ul>
					<button
						onClick={async () => {
							const isMerging = await checkLocalMergeStatus();
							if (isMerging) {
								const conflictFileList = await getLocalConflictFileList();
								setConflictFileList(conflictFileList);
								// 已经解决冲突
								if (conflictFileList.length === 0) {
									await mergeCommitAndPush();
									await refresh();
								}
							} else {
								await mergeBranch({ head: mrState.head, base: mrState.base });
							}
							setIsMerging(isMerging);
						}}
					>
						{isMerging && conflictFileList?.length === 0 ? '提交代码并推送' : '点击解决冲突'}
					</button>
				</div>
			)}
			<div className="branch-info">
				<div className="branch-name">
					<RepoIcon className="branch-icon" /> 来源分支：{mrState.base}
				</div>
				<div className="branch-name">
					<GitCompareIcon className="branch-icon" /> 目标分支：{mrState.head}
				</div>
			</div>
			{mrState.status === CodingMergeRequestState.ACCEPTED
				&& (<div style={{ display: 'flex', marginBottom: '10px' }}>
					<button style={{ width: '100%' }} disabled={isBusy} className="secondary" onClick={exitReviewMode}>返回默认分支</button>
				</div>)}
			{!disabled && (
				<textarea
					disabled={isBusy || disabled}
					placeholder={'Leave a comment'}
					value={mrState.pendingCommentText}
					onChange={onChangeTextarea}
				></textarea>
			)}
			{!disabled && (
				<section>
					<button disabled={isBusy || disabled} className="comment-resolve" onClick={approveHandler}>
						通过
					</button>
					<button disabled={isBusy || disabled} className="secondary" onClick={closeHandler}>
						关闭
					</button>
				</section>
			)}
		</div>
	);
};
