import Image from 'next/image'
import * as _ from 'underscore'
import styles from './style.module.css'
import { useCallback, useContext, useEffect, useMemo, useState } from 'react'
import { Dropdown, MenuProps, Spin } from 'antd'
import AppContext from '@/components/hooks/createContext'
import { replicableExecutions, executionFaceDetect, getTaskDetail } from '@/pages/api/base'
import { IReplicableExecution } from '@/pages/api/base/type'
import CustomModal from '@/components/Modal'
import CustomLink from '@/components/CustomLink'
import Toast from '@/components/Toast'
import { useTranslation } from 'next-i18next'
import { previewLoader } from '@/common/utils'
import { RETASK_BLOG_LINK, RETASK_BLOG_TEXT } from '@/common/constans/international'
import { PARAMS } from '@/components/hooks/constants'

type FaceDetectStatus = 'Pending' | 'Pass' | 'Fail' | 'None'

const Replicate = () => {
    const { t } = useTranslation('studio')

    const {
        taskResult: [taskResult],
        handleTaskResult,
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    } = useContext(AppContext)!

    const [detectStatus, setDetectStatus] = useState<FaceDetectStatus>('None')
    const [taskNo, setTaskNo] = useState<string>('')
    const [executions, setExecutions] = useState<IReplicableExecution[]>([])
    const [executionMsg, setExecutionMsg] = useState<string>('')

    useEffect(() => {
        const taskNo = taskResult.replicateFromTaskNo
        setTaskNo(`${taskNo ? taskNo : ''}`)
        if (taskNo) {
            setExecutions([])
            getReplicableExecutions(taskNo)
        }
    }, [taskResult.replicateFromTaskNo])

    const getReplicableExecutions = async (taskNo: number) => {
        try {
            const resp = await replicableExecutions({
                taskNo,
                noShowToast: true,
                replicateList: true,
            })
            if (resp?.list) {
                setExecutions(resp.list ?? [])
                setExecutionMsg('')
            } else if (resp.code) {
                setExecutionMsg(resp.msg)
            }
        } catch (error) {
            console.error(error)
        }
    }

    useEffect(() => {
        if (taskResult.replicateFromTaskNo && taskResult.replicateFromExecuteSeq) {
            setDetectStatus('Pending')
        } else {
            setDetectStatus('None')
        }
    }, [taskResult.replicateFromExecuteSeq])

    useEffect(() => {
        const unitId = executions?.find((item) => {
            return item.executeSeq == taskResult.replicateFromExecuteSeq
        })?.results[0]?.unitId
        if (detectStatus === 'Pending' && unitId) {
            const faceDetect = async () => {
                try {
                    const resp = await executionFaceDetect({ unitId })
                    if (resp) {
                        setDetectStatus(resp.status)
                        if (resp.status == 'Error') {
                            Toast({ message: t('toast.systemError') })
                        }
                    } else {
                        setDetectStatus('None')
                    }
                } catch (error) {
                    console.error(error)
                    setDetectStatus('None')
                }
            }
            faceDetect()
            const intervalId = setInterval(faceDetect, 2000)
            return () => {
                clearInterval(intervalId)
            }
        }
    }, [detectStatus, executions])

    const closeFailModal = (open: boolean) => {
        if (!open) {
            handleTaskResult('replicateFromImage', null, true)
            handleTaskResult('replicateFromUnitId', null, true)
            handleTaskResult('replicateFromTaskAgentName', null, true)
            handleTaskResult('replicateFromExecuteSeq', 0, true)
            handleTaskResult('replicateFromTaskNo', 0)
        }
    }

    const executeSeqItems = useMemo<MenuProps['items']>(() => {
        return executions.map((item) => {
            return { key: item.executeSeq, label: item.executeSeq }
        })
    }, [executions])

    const executeSeqMenuClick: MenuProps['onClick'] = (e) => {
        const executionSeq = e.key
        if (parseInt(executionSeq) != taskResult.replicateFromExecuteSeq) {
            handleTaskResult('replicateFromUnitId', null, true)
            handleTaskResult('replicateFromImage', null, true)
            handleTaskResult('replicateFromTaskAgentName', null, true)
            handleTaskResult('replicateFromExecuteSeq', parseInt(executionSeq))
        }
    }

    const figureIndexItems = useMemo<MenuProps['items']>(() => {
        const seq = taskResult.replicateFromExecuteSeq
        if (seq) {
            return executions
                ?.find((it) => {
                    return it.executeSeq == seq
                })
                ?.results?.map((item, index) => {
                    return { key: `${item.unitId}`, label: `${index + 1}` }
                })
        }
    }, [executions, taskResult.replicateFromExecuteSeq])

    const figureIndex = useMemo<string>(() => {
        const seq = taskResult.replicateFromExecuteSeq
        const unitId = taskResult.replicateFromUnitId
        if (seq && unitId) {
            const execution = executions?.find((it) => {
                return it.executeSeq == seq
            })
            if (execution) {
                const image = execution.results?.find((it) => {
                    return it.unitId == unitId
                })
                if (image) {
                    return `${execution.results.indexOf(image) + 1}`
                }
            }
        }
        return ''
    }, [executions, taskResult.replicateFromExecuteSeq, taskResult.replicateFromUnitId])

    const figureIndexMenuClick: MenuProps['onClick'] = (e) => {
        const unitId = e.key
        const result = executions
            .find((it) => {
                return it.executeSeq == taskResult.replicateFromExecuteSeq
            })
            ?.results?.find((it) => {
                return it.unitId == unitId
            })
        if (result) {
            handleTaskResult('replicateFromUnitId', result.unitId, true)
            handleTaskResult('replicateFromImage', result.image)
        }
    }

    const taskNoChange = useCallback(
        _.debounce((taskNo: string) => {
            // 这里节流函数设置taskNo
            handleTaskResult('replicateFromImage', null, true)
            handleTaskResult('replicateFromUnitId', null, true)
            handleTaskResult('replicateFromTaskAgentName', null, true)
            handleTaskResult('replicateFromExecuteSeq', 0, true)
            handleTaskResult('replicateFromTaskNo', parseInt(taskNo))
        }, 500),
        [],
    )

    useEffect(() => {
        const taskNo = taskResult.replicateFromTaskNo
        const seq = taskResult.replicateFromExecuteSeq
        if (taskNo && seq) {
            const executionInfo = executions.find((it) => it.executeSeq == seq)
            if (
                executionInfo &&
                executionInfo.taskId &&
                executionInfo.executionId &&
                !taskResult.replicateFromTaskAgentName
            ) {
                getReplicateTaskDetail(executionInfo.taskId, executionInfo.executionId)
            }
        }
    }, [taskResult.replicateFromTaskNo, taskResult.replicateFromExecuteSeq, executions])

    const getReplicateTaskDetail = async (taskId: string, executionId: string) => {
        let taskDetail = await getTaskDetail({ taskId, executionId })
        if (taskDetail.paramType === 'replicate') {
            const resp = await replicableExecutions({
                taskNo: taskDetail.replicateFromTaskNo,
                noShowToast: true,
                replicateList: true,
            })
            if (resp?.list) {
                const execution = resp.list?.find((item) => {
                    return item.executeSeq == taskDetail.replicateFromExecuteSeq
                })
                taskDetail = await getTaskDetail({
                    taskId: execution.taskId,
                    executionId: execution.executionId,
                })
            }
        }
        handleTaskResult(
            'replicateFromTaskAgentName',
            taskDetail.agentName === 'replicate'
                ? taskDetail.replicateFromTaskAgentName
                : taskDetail.agentName,
            true,
        )
        PARAMS[taskDetail.paramType]?.forEach((item: string) => {
            handleTaskResult(item, taskDetail[item], true)
        })
        handleTaskResult('paramType', taskDetail.paramType)
        handleTaskResult('agentVersion', taskDetail.agentVersion)
    }

    const phrase = [
        t('retask.phrase1'),
        t('retask.phrase2'),
        t('retask.phrase3'),
        t('retask.phrase4'),
    ]

    return (
        <>
            <Spin spinning={detectStatus === 'Pending'} delay={100}>
                <div className={styles.replicateContainer}>
                    <div className={styles.replicateNoContainer}>
                        <div className={styles.input}>
                            <div className={styles.inputTaskContainer}>
                                <label className={`ag14 ${styles.label}`}>
                                    {t('retask.taskNumber')}
                                </label>
                                <input
                                    className={`${styles.inputValue} ag16`}
                                    type={'text'}
                                    placeholder={''}
                                    value={taskNo}
                                    onChange={(e) => {
                                        const taskNo = e.target.value
                                        setTaskNo(taskNo)
                                        taskNoChange(taskNo)
                                    }}
                                />
                            </div>
                            <div className={styles.inputSplit}>
                                <div>-</div>
                            </div>
                            <div className={styles.inputContainer}>
                                <label className={`ag14 ${styles.label}`}>
                                    {t('retask.executionCount')}
                                </label>
                                {executionMsg ? (
                                    <div
                                        className={`${styles.selectValue} ag16`}
                                        onClick={() => {
                                            Toast({
                                                message: `🔴 ${executionMsg} 🙅🏻‍♀️`,
                                                duration: 2000,
                                            })
                                        }}
                                    >
                                        <span> </span>
                                        <Image
                                            src={'/task-dropdown.svg'}
                                            alt="dropdown"
                                            height={32}
                                            width={32}
                                        ></Image>
                                    </div>
                                ) : (
                                    <Dropdown
                                        menu={{
                                            items: executeSeqItems,
                                            onClick: executeSeqMenuClick,
                                        }}
                                        overlayClassName={styles.dropdown}
                                        trigger={['click']}
                                        disabled={!executeSeqItems?.length}
                                    >
                                        <div
                                            className={`${styles.selectValue} ag16`}
                                            onClick={(e) => e.preventDefault()}
                                        >
                                            <span>
                                                {taskResult.replicateFromExecuteSeq
                                                    ? taskResult.replicateFromExecuteSeq
                                                    : ''}
                                            </span>
                                            <Image
                                                src={'/task-dropdown.svg'}
                                                alt="dropdown"
                                                height={32}
                                                width={32}
                                            ></Image>
                                        </div>
                                    </Dropdown>
                                )}
                            </div>
                            <div className={styles.inputSplit}>
                                <div>-</div>
                            </div>
                            <div className={styles.inputContainer}>
                                <label className={`ag14 ${styles.label}`}>
                                    {t('retask.figureIndex')}
                                </label>
                                <Dropdown
                                    menu={{
                                        items: figureIndexItems,
                                        onClick: figureIndexMenuClick,
                                    }}
                                    overlayClassName={styles.dropdown}
                                    trigger={['click']}
                                    disabled={!figureIndexItems?.length}
                                >
                                    <div
                                        className={`${styles.selectValue} ag16`}
                                        onClick={(e) => e.preventDefault()}
                                    >
                                        <span>{figureIndex}</span>
                                        <Image
                                            src={'/task-dropdown.svg'}
                                            alt="dropdown"
                                            height={32}
                                            width={32}
                                        ></Image>
                                    </div>
                                </Dropdown>
                            </div>
                        </div>
                        <div className={styles.content}>
                            <p className={`ag14-t ${styles.contentTitle}`}>{t('retask.hint2')}</p>
                            {phrase.map((item, index) => (
                                <div className={`ag14 ${styles.contentDesc}`} key={index}>
                                    <div style={{ width: '18px', paddingLeft: '2px' }}>
                                        {index + 1}.
                                    </div>
                                    <div style={{ flex: 1 }}>{item}</div>
                                </div>
                            ))}
                            {RETASK_BLOG_LINK ? (
                                <div className={styles.linkContainer}>
                                    <span>{t('retask.tutorial')}</span>
                                    <CustomLink href={RETASK_BLOG_LINK} target={'_blank'}>
                                        <span className={styles.link}>{RETASK_BLOG_TEXT}</span>
                                    </CustomLink>
                                </div>
                            ) : null}
                        </div>
                    </div>
                    <div className={styles.replicateImageContainer}>
                        {taskResult.replicateFromImage ? (
                            <>
                                <Image
                                    src={taskResult.replicateFromImage}
                                    width={384}
                                    height={384}
                                    className={styles.replicateImage}
                                    alt="replicate_image"
                                    loader={previewLoader}
                                />
                                <span className={`ag14 ${styles.replicateImageHint}`}>
                                    {t('retask.picHint')}
                                </span>
                            </>
                        ) : (
                            <>
                                <div
                                    style={{ width: '384px', height: '384px' }}
                                    className={styles.replicateImageNone}
                                ></div>
                                <span className={`ag14 ${styles.replicateImageHint}`}> </span>
                            </>
                        )}
                    </div>
                </div>
            </Spin>
            {detectStatus === 'Fail' ? (
                <CustomModal
                    isModalOpen={detectStatus === 'Fail'}
                    setIsModalOpen={closeFailModal}
                    width={408}
                    title={t('retask.failTitle')}
                >
                    <div className={`ag14 ${styles.failContent}`}>{t('retask.failContent')}</div>
                    <div
                        className={styles.btnChoose}
                        onClick={() => {
                            closeFailModal(false)
                        }}
                    >
                        {t('confirm')}
                    </div>
                </CustomModal>
            ) : null}
        </>
    )
}

export default Replicate
