import styles from './style.module.css'
import { useContext, useRef, useState } from 'react'
import AppContext from '../../../hooks/createContext'
import { verfiyInfer } from '@/common/utils'
import Button from '@/components/Button'
import { runTask } from '@/pages/api/base'
import PowerDefect from './components/PowerDefect'
import { useTranslation } from 'next-i18next'
import Image from 'next/image'
import SDImg from '@/components/Ground/SDImg'
import Maximize from './components/Maximize'
import { SHOW_COMPUTER_POWER } from '@/common/constans/international'
import BatchPowerDetail from './components/BatchPowerDetail'
import AgentVersionSelect from './components/AgentVersion'
import CommonTask from './components/CommonTask'
import { DEFAULT_AGENT_TIPS } from '@/common/constans'

interface Iprops {
    infer: () => void
}

const Edit = ({ infer }: Iprops) => {
    const { t } = useTranslation('studio')

    const {
        userInfos: [userInfos],
        taskResult: [taskResult],
        saveTaskDetail,
        agentName: [agentName],
        requestLoading: [, setRequestLoading],
        taskId: [taskId],
        powerBalanceAmount: [, setPowerBalance],
        needPower: [needPower],
        samMask,
        batchTaskPowerDetail: [batchTaskPowerDetail],
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    } = useContext(AppContext)!

    const [isModalOpen, setIsModalOpen] = useState(false)
    const isSubmitting = useRef(false)

    // 提交任务
    const handleInfer = async () => {
        if (isSubmitting.current) {
            return
        }
        if (!verfiyInfer(taskResult, t)) return
        isSubmitting.current = true
        setRequestLoading(true)
        try {
            if (taskResult.mask) await samMask(taskResult.mask) // 需要主动调用一下save mask
            const value = (await saveTaskDetail()) as any
            if (value?.taskId) {
                const data = await runTask({
                    taskId,
                    agentName: agentName ?? '',
                    agentVersion: taskResult?.agentVersion,
                })
                if (data?.taskId) {
                    setPowerBalance(data?.powerBalanceAmount)
                    infer()
                } else if (data?.code === '2007') {
                    setRequestLoading(false)
                    setIsModalOpen(true)
                }
            }
        } catch (e) {
            console.info(e)
        } finally {
            isSubmitting.current = false
            setRequestLoading(false)
        }
    }

    const renderComponents = () => {
        switch (agentName) {
            case 'image2image':
            case 'text2image':
                return <SDImg></SDImg>
            case 'upscale':
                return <Maximize></Maximize>
            default:
                return <CommonTask></CommonTask>
        }
    }
    return (
        <div className={styles.edit} id="myEdit">
            {renderComponents()}
            <div className={styles.opreate} id="opreate">
                <div className={styles.computerPowerWrap}>
                    {SHOW_COMPUTER_POWER ? (
                        <span className={`${styles.consumeTip} ag14`}>
                            <span>{t('taskConsume')}</span>
                            <Image
                                src="/cpu-charge.svg"
                                width={20}
                                height={20}
                                alt="cpu-charge"
                                className={styles.cpuCharge}
                            ></Image>
                            <span className={styles.consumeHighlightTip}>{needPower}</span>
                            <span>{t('computerPower')}</span>
                        </span>
                    ) : null}

                    {taskResult?.batchTask && batchTaskPowerDetail ? (
                        <BatchPowerDetail></BatchPowerDetail>
                    ) : null}
                </div>

                <div className={styles.generate}>
                    <Button
                        style={{ fontWeight: '500', flex: 1 }}
                        onClick={() => {
                            handleInfer()
                        }}
                    >
                        {t('generate')}
                    </Button>
                    {DEFAULT_AGENT_TIPS[agentName || '']?.isSupportChangeVersion &&
                    userInfos?.agent15 ? (
                        <AgentVersionSelect></AgentVersionSelect>
                    ) : null}
                </div>
            </div>
            {isModalOpen && (
                <PowerDefect
                    isModalOpen={isModalOpen}
                    setIsModalOpen={setIsModalOpen}
                ></PowerDefect>
            )}
        </div>
    )
}

export default Edit
