import styles from './style.module.css'
import Image from 'next/image'
import { useContext, useState, useEffect } from 'react'
import AppContext from '@/components/hooks/createContext'
import NewGenerateMask from '@/components/NewGenerateMask/index'
import { loadImage } from '@/common/utils'
import Toast from '@/components/Toast'
import UploadMask from '../UploadMask'
import { useTranslation } from 'next-i18next'
import { getBodySegment, getSegement, updateSegment } from '@/pages/api/base'
import { Spin } from 'antd'
import { MAIN_CUT_AGENT } from '@/common/constans'

interface Iscale {
    width: number
    height: number
}

interface IProps {
    setUploadingMask: (loading: boolean) => void
    showDisable?: boolean
    disableEdit?: () => void
}

const EditMask = ({
    setUploadingMask,
    showDisable = false,
    disableEdit = () => {
        console.info('')
    },
}: IProps) => {
    const { t } = useTranslation('studio')
    const {
        agentName: [agentName],
        showEdit: [showEdit],
        taskId: [taskId],
        taskResult: [taskResult],
        segementModal: [segementModal, setSegmentModal],
        mainCutMask: [, setMainCutMask],
        handleTaskResult,
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    } = useContext(AppContext)!

    const [iWidth, setIwidth] = useState(0)
    const [iHeight, setIheight] = useState(0)
    const [imageData, setImageData] = useState([])
    const [mainCutImageData, setMainCutImageData] = useState({ taskId: '' })
    const [btnStatus, setBtnStatus] = useState('')

    const [btnAtrr, setBtnAtrr] = useState({
        icon: '/loading.svg',
        text: t('editMask.selectionLoading'),
        className: `${styles.loading}`,
        imageClassName: `${styles.editIcon} progressLoading`,
    })

    const isMainCut: boolean = MAIN_CUT_AGENT.includes(agentName as string)

    const [key, setKey] = useState(false)
    const [flag, setFlag] = useState(true)

    const [mainCutLoading, setMainCutLoading] = useState<boolean>(false)
    const [startSegement, setStartSegement] = useState<boolean>(false)

    const [currentTaskId, setCurrentTaskId] = useState<string>('')

    const handleEdit = async () => {
        // 编辑选区打点
        const logParam = window?.logger.getParams('10000005', window?.logger.EVENT_TYPE.CLICK, {
            taskId,
            agentName,
            type: 1,
        })
        window?.logger.log([logParam])
        if (
            !imageData ||
            !taskResult?.showImage ||
            btnStatus !== 'Success' ||
            currentTaskId !== taskResult?.taskId
        )
            return
        const { width, height } = (await loadImage(taskResult?.showImage)) as Iscale
        if (width && height) {
            setIheight(height)
            setIwidth(width)
            setSegmentModal(true)
        } else {
            Toast({ message: t('toast.modelDownloadFail') })
        }
    }

    const reload = async () => {
        if (btnStatus !== 'Success' && flag) {
            await updateSegment({ image: taskResult.showImage || '', taskId })
            setKey(!key)
            setFlag(false)
        }
    }

    const getMaskData = async (intervalId?: NodeJS.Timeout | null) => {
        const value = await getSegement({
            taskId,
            image: taskResult?.showImage || '',
            noShowToast: true,
        })
        if (value) {
            setImageData(JSON.parse(value.data))
            setBtnStatus(value.status)
            setCurrentTaskId(value.taskId)
            if (intervalId) {
                setFlag(true)
                if (value.status !== 'Segmenting') clearInterval(intervalId)
            }
        }
    }

    const mainCutData = async (intervalId?: NodeJS.Timeout | null) => {
        setMainCutLoading(true)
        const value = await getBodySegment({
            taskId,
            image: taskResult?.showImage || '',
            noShowToast: true,
        })
        setMainCutImageData(value)
        if (value?.base64Mask) {
            if (value?.taskId === taskResult?.taskId && !taskResult?.mask) {
                // 主体分割的mask无需保存
                handleTaskResult('mask', value.base64Mask, true)
                setMainCutMask(value.base64Mask)
            }
        } else if (value?.status === 'Closed' && !taskResult?.mask) {
            Toast({ message: t('toast.mainError') })
        }

        if (value.status !== 'Segmenting') {
            if (intervalId) clearInterval(intervalId)
            setMainCutLoading(false)
        }
    }

    useEffect(() => {
        if (isMainCut) handleEdit()
        if (btnStatus === 'Success' || btnStatus === 'Default') {
            btnAtrr.className = `${styles.successBtn}`
            btnAtrr.text = t('editMask.selectionEdit')
            btnAtrr.icon = '/edit-2.svg'
            btnAtrr.imageClassName = `${styles.editIcon}`
        } else if (btnStatus === 'OutOfDate' || btnStatus === 'Error') {
            btnAtrr.className = `${styles.successBtn}`
            btnAtrr.text = t('editMask.selectionRefresh')
            btnAtrr.icon = '/refresh.svg'
            btnAtrr.imageClassName = `${styles.editIcon}`
        } else if (btnStatus === 'Segmenting') {
            btnAtrr.className = `${styles.loading}`
            btnAtrr.text = t('editMask.selectionLoading')
            btnAtrr.icon = '/loading.svg'
            btnAtrr.imageClassName = `${styles.loadingIcon} progressLoading`
        }
        setBtnAtrr({ ...btnAtrr })
    }, [btnStatus])

    useEffect(() => {
        if (startSegement || !isMainCut || taskResult?.segmentStatus === 'Segmenting') {
            setBtnStatus('')
            setImageData([])
            let isRequestCompleted = true
            const fetchMaskData = async (intervalId?: NodeJS.Timeout | null) => {
                try {
                    if (startSegement) setStartSegement(false)
                    await getMaskData(intervalId)
                } catch (error) {
                    console.error(error)
                }
                isRequestCompleted = true
            }
            if (showEdit && taskResult?.showImage && taskId) {
                isRequestCompleted = false
                fetchMaskData(null)
                const intervalId1 = setInterval(() => {
                    if (isRequestCompleted) {
                        isRequestCompleted = false
                        fetchMaskData(intervalId1)
                    }
                }, 2000)
                return () => clearInterval(intervalId1)
            }
        }
    }, [taskResult?.showImage, key, showEdit])

    useEffect(() => {
        if (!(startSegement || !isMainCut)) {
            setBtnStatus('Default')
            let isMainCutRequestCompleted = true
            const fetchMainCutMaskData = async (intervalId?: NodeJS.Timeout | null) => {
                try {
                    await mainCutData(intervalId)
                } catch (error) {
                    console.error(error)
                }
                isMainCutRequestCompleted = true
            }
            if (showEdit && taskResult?.showImage && taskId) {
                isMainCutRequestCompleted = false

                fetchMainCutMaskData(null)
                const intervalId2 = setInterval(() => {
                    if (isMainCutRequestCompleted) {
                        isMainCutRequestCompleted = false
                        fetchMainCutMaskData(intervalId2)
                    }
                }, 2000)
                return () => clearInterval(intervalId2)
            }
        }
    }, [taskResult?.showImage, showEdit])

    return (
        <>
            {taskResult?.mask ? (
                <div className={styles.maskBg}>
                    {taskResult?.showImage ? (
                        <Image
                            src={taskResult?.showImage}
                            alt="origin"
                            width={384}
                            height={384}
                            className={styles.originImag}
                            unoptimized
                            key={taskResult?.showImage}
                        ></Image>
                    ) : null}

                    <Image
                        src={taskResult?.mask}
                        alt="edit"
                        width={384}
                        height={384}
                        className={styles.maskImg}
                        unoptimized
                    ></Image>
                </div>
            ) : (
                <div className={styles.empty}>
                    {taskResult.image ? (
                        <div className={styles.editEmpty}>
                            <>
                                {mainCutLoading ? (
                                    <>
                                        <Spin
                                            spinning={mainCutLoading}
                                            size="large"
                                            className={styles.editEmptySpin}
                                        ></Spin>
                                    </>
                                ) : (
                                    <>
                                        <Image
                                            src="/gallery-tick.svg"
                                            alt="edit"
                                            width={24}
                                            height={24}
                                        ></Image>
                                        <p className={styles.editTitle}>
                                            {t('editMask.editSelection')}
                                        </p>
                                        <p className={`${styles.editSubTitle} ag14`}>
                                            {showDisable
                                                ? t('editMask.editSelectionHint2')
                                                : t('editMask.editSelectionHint')}
                                        </p>
                                    </>
                                )}
                            </>
                        </div>
                    ) : null}
                </div>
            )}
            {taskResult.image ? (
                <div className={`ag14 ${styles.editAndUpload}`}>
                    <div
                        onClick={() => {
                            if (btnStatus === 'Success') {
                                handleEdit()
                            } else if (btnStatus === 'OutOfDate' || btnStatus === 'Error') {
                                reload()
                            } else if (btnStatus === 'Default') {
                                setStartSegement(true)
                                setKey(!key)
                            }
                        }}
                        className={`${styles.editBtn} ${btnAtrr.className}`}
                    >
                        <Image
                            src={btnAtrr.icon}
                            alt="edit-icon"
                            width={14}
                            height={14}
                            className={btnAtrr.imageClassName}
                        ></Image>
                        {btnAtrr.text}
                    </div>
                </div>
            ) : null}
            <div className={styles.maskText}>
                <span>{t('editMask.selection')}</span>
                {taskResult.image ? (
                    <div>
                        <span className={styles.or}>{t('editMask.selectionOr')}</span>
                        <UploadMask setUploading={setUploadingMask}></UploadMask>
                    </div>
                ) : null}
            </div>

            {showDisable ? (
                <div className={styles.delete} onClick={disableEdit}>
                    <Image
                        src={'/modal-close.svg'}
                        width={16}
                        height={16}
                        alt="disableMask"
                    ></Image>
                </div>
            ) : null}

            {segementModal ? (
                <NewGenerateMask
                    key={taskId}
                    iWidth={iWidth}
                    iHeight={iHeight}
                    imageData={imageData}
                    mainCutImageData={mainCutImageData}
                ></NewGenerateMask>
            ) : null}
        </>
    )
}

export default EditMask
