import Image from 'next/image'
import * as _ from 'underscore'
import styles from './style.module.css'
import { useCallback, useContext, useEffect, useState } from 'react'
import { Dropdown, MenuProps, Spin } from 'antd'
import AppContext from '@/components/hooks/createContext'
import { replicableExecutions, executionFaceDetect } 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'

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

const Retask = () => {
    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>('')

    const editable = false

    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 })
            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])

    const setIntervalEx = (callback: (args: void) => void, ms?: number): NodeJS.Timer => {
        callback()
        return setInterval(callback, ms)
    }

    useEffect(() => {
        let intervalId: NodeJS.Timeout | null = null
        const unitId = executions?.find((item) => {
            return item.executeSeq == taskResult.replicateFromExecuteSeq
        })?.results[0]?.unitId
        if (detectStatus === 'Pending' && unitId) {
            intervalId = setIntervalEx(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')
                }
            }, 2000)
            return () => {
                if (intervalId) clearInterval(intervalId)
            }
        }
    }, [detectStatus, executions])

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

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

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

    const inputIdChange = useCallback((e) => {
        const taskNo = e.target.value
        setTaskNo(taskNo)
        taskNoChange(taskNo)
    }, [])

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

    const execution = executions.find((item) => {
        return item.executeSeq == taskResult.replicateFromExecuteSeq
    })

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

    return (
        <>
            <Spin spinning={detectStatus === 'Pending'} delay={100}>
                <div className={styles.retaskContainer}>
                    <div className={styles.input}>
                        <div className={styles.inputContainer}>
                            <label className={`ag14`}>{t('retask.taskNumber')}</label>
                            {editable ? (
                                <input
                                    className={`${styles.inputValue} ag16`}
                                    type={'text'}
                                    placeholder={''}
                                    value={taskNo}
                                    onChange={inputIdChange}
                                />
                            ) : (
                                <div className={`${styles.inputValue0} ag16`}>
                                    <span>{taskNo}</span>
                                </div>
                            )}
                        </div>
                        <div className={styles.inputSplit}>
                            <div>-</div>
                        </div>
                        <div className={styles.inputContainer}>
                            <label className={`ag14`}>{t('retask.executionCount')}</label>
                            {editable ? (
                                <>
                                    {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,
                                                onClick: handleMenuClick,
                                            }}
                                            overlayClassName={styles.dropdown}
                                            trigger={['click']}
                                            disabled={executions.length == 0}
                                        >
                                            <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 className={`${styles.selectValue0} ag16`}>
                                    <span>
                                        {taskResult.replicateFromExecuteSeq
                                            ? taskResult.replicateFromExecuteSeq
                                            : ''}
                                    </span>
                                </div>
                            )}
                        </div>
                    </div>
                    {execution ? (
                        <div className={`ag14 ${styles.imgHint}`}>{t('retask.modelSelect')}</div>
                    ) : null}
                    <div className={styles.imgContainer}>
                        {execution
                            ? execution?.results.map((item, index) => {
                                  return (
                                      <div
                                          className={`${
                                              editable ? styles.imgWrapper : styles.imgWrapper0
                                          } ${
                                              item.unitId == taskResult.replicateFromUnitId
                                                  ? styles.selected
                                                  : ''
                                          }`}
                                          onClick={() => {
                                              if (editable) {
                                                  handleTaskResult(
                                                      'replicateFromUnitId',
                                                      item.unitId,
                                                  )
                                                  handleTaskResult('replicateFromImage', item.image)
                                              }
                                          }}
                                          key={index}
                                      >
                                          <Image
                                              src={item.image}
                                              alt="execution-result"
                                              width={184}
                                              height={245}
                                              className={styles.img}
                                              loader={previewLoader}
                                          ></Image>
                                      </div>
                                  )
                              })
                            : null}
                    </div>
                    <div className={styles.content}>
                        <p className={`ag14-t ${styles.contentTitle}`}>{t('retask.hint1')}</p>
                        <p className={`ag14-t ${styles.contentTitle}`}>{t('retask.hint2')}</p>
                        <ul className={`ag14 ${styles.contentDesc}`}>
                            {phrase.map((item, index) => (
                                <li key={index}>{item}</li>
                            ))}
                        </ul>
                        {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>
            </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 Retask
