import CustomSelect from '@/components/CustomSelect'
import styles from './style.module.css'
import { useContext, useEffect, useState } from 'react'
import CustomSlider from '@/components/CustomSlider'
import CustomTag from '@/components/CustomTag'
import GenerateSize from '../GenerateSize'
// import ImgReference from '../ImgReference'
import AppContext from '@/components/hooks/createContext'
import TextPrompt from '@/components/Nav/components/Edit/components/TextPrompt'
import Lora from '../Lora'
import Controller from '../Controller'
import { getGroundParams } from '@/pages/api/base'
import ImgReference from '../ImgReference'
import ADetail from '../ADetail'
import { useTranslation } from 'next-i18next'
import Seed from '../Seed'
import Toast from '@/components/Toast'
import HiresFix from '../HiresFix'

interface paramsType {
    id: string
    name: string
}

const SDImg = () => {
    const { t } = useTranslation('studio')
    const {
        agentName: [agentName],
        taskResult: [taskResult],
        handleTaskResult,
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    } = useContext(AppContext)!

    const [configs, setConfigs] = useState<any[]>([])

    useEffect(() => {
        setGroundParams()
    }, [taskResult])

    const refershGroundParams = async () => {
        const suc = await setGroundParams()
        if (suc) {
            Toast({ message: t('sd.refreshSuccessful'), type: 'success' })
        }
    }

    const handleOptions = (data: paramsType[], key: string, value: string) => {
        const obj = data?.map((item: paramsType) => {
            return { [key]: item.name, [value]: item.id }
        })
        return obj
    }

    const setGroundParams = async () => {
        if (!agentName) return false
        const value = await getGroundParams({ agentName })
        if (!value) return false

        const tempConfig = [
            {
                type: 'selector',
                label: 'CHECKPOINT',
                key: taskResult.batchTask ? 'sdCheckpoints' : 'sdCheckpoint',
                width: 49,
                mode: taskResult.batchTask ? 'multiple' : undefined,
                options: value?.sdCheckpoint?.map((item) => {
                    return {
                        label: item.name,
                        value: item.id,
                        popover: {
                            title: t('sd.modelDisclaimer'),
                            content: item.commercialDescription,
                        },
                    }
                }),
            },
            {
                type: 'selector',
                label: 'VAE',
                key: 'sdVae',
                width: 37,
                options: handleOptions(value?.sdVae, 'label', 'value'),
            },
            {
                type: 'selector',
                label: 'Clip Skip',
                key: 'sdClipStopAtLastLayers',
                width: 10,
                options: handleOptions(value?.sdClipStopAtLastLayers, 'label', 'value'),
            },
            { type: 'imageReference', key: 'imageReference', value: value },
            { type: 'prompt' },
            { type: 'lora', key: 'sdLora', options: value?.sdLora },
            {
                type: 'selector',
                label: t('sd.samplingMethod'),
                key: taskResult.batchTask ? 'sdSamplingMethods' : 'sdSamplingMethod',
                mode: taskResult.batchTask ? 'multiple' : undefined,
                width: 49,
                options: handleOptions(value?.sdSamplingMethod, 'label', 'value'),
            },
            {
                type: 'tag',
                key: 'sdSamplingSteps',
                label: t('sd.samplingSteps'),
                width: 49,
                options: handleOptions(value?.sdSamplingSteps, 'key', 'value'),
            },
            {
                type: 'tag',
                key: 'sdRestoreFaces',
                label: t('sd.restoreFaces'),
                options: [
                    { key: 1, value: t('sd.true') },
                    { key: 0, value: t('sd.false') },
                ],
            },
            {
                type: 'generateSize',
                key: 'sdWidthAndHeight',
                maxSize: {
                    width: value?.sdWidthAndHeight?.maxWidth,
                    height: value?.sdWidthAndHeight?.maxHeight,
                },
                options: value?.sdWidthAndHeight?.options,
            },
            {
                type: 'tag',
                key: 'batchCount',
                label: t('sd.batchCount'),
                options: handleOptions(value?.batchCount, 'key', 'value'),
            },
            {
                type: 'slider',
                key: 'sdCfgScale',
                label: t('sd.cgfScale'),
                config: value?.sdCfgScale?.range,
            },
            {
                type: 'slider',
                key: 'sdDenoisingStrength',
                label: t('sd.denoisingStrength'),
                config: value?.sdDenoisingStrength?.range,
            },
            {
                type: 'seed',
                key: 'sdSeed',
            },
            {
                type: 'hiresFix',
                key: 'sdHrEnable',
            },
            { type: 'controller', key: 'sdController', options: value?.sdController },
            { type: 'aDetail', key: 'sdADetail' },
        ]
        setConfigs(
            tempConfig.filter(
                (item) =>
                    (agentName == 'image2image' && item.key != 'sdHrEnable') ||
                    (agentName == 'text2image' &&
                        item.key != 'sdDenoisingStrength' &&
                        item.key != 'imageReference'),
            ),
        )
        return true
    }

    return (
        <div className={styles.modelContainer}>
            {configs.map((item, index) => {
                return (
                    <>
                        {item.type === 'controller' || item.type === 'aDetail' ? (
                            <div className={styles.divider}>
                                <div className={styles.line}></div>
                            </div>
                        ) : null}
                        <div
                            className={styles.modelItem}
                            key={index}
                            style={{ width: `${item.width ?? 100}%` }}
                        >
                            {item.type === 'selector' ? (
                                <CustomSelect
                                    value={taskResult[item.key]}
                                    onChange={(value) => {
                                        handleTaskResult(item.key, value)
                                    }}
                                    options={item.options}
                                    label={item.label}
                                    refersh={
                                        item.key == 'sdCheckpoint' || item.key == 'sdVae'
                                            ? refershGroundParams
                                            : null
                                    }
                                    mode={item?.mode || ''}
                                ></CustomSelect>
                            ) : item.type === 'prompt' ? (
                                <TextPrompt isNotShowExplain={true}></TextPrompt>
                            ) : item.type === 'lora' ? (
                                <Lora
                                    list={item.options}
                                    refershParams={refershGroundParams}
                                    selectedLoras={taskResult['sdLora']}
                                    submitLoras={(it) => {
                                        handleTaskResult('sdLora', it)
                                    }}
                                ></Lora>
                            ) : item.type === 'tag' ? (
                                <CustomTag
                                    options={item.options}
                                    value={[taskResult[item.key]]}
                                    onChange={(value) => {
                                        handleTaskResult(item.key, value)
                                    }}
                                    label={item.label}
                                ></CustomTag>
                            ) : item.type === 'generateSize' ? (
                                <GenerateSize
                                    needMulti={false}
                                    maxSize={item.maxSize}
                                    size={taskResult[item.key]}
                                    sizeOptions={item.options ?? []}
                                    sizeChange={(value) => {
                                        handleTaskResult(item.key, value)
                                    }}
                                ></GenerateSize>
                            ) : item.type === 'slider' ? (
                                <CustomSlider
                                    value={taskResult[item.key]}
                                    valueChange={(value) => {
                                        handleTaskResult(item.key, value)
                                    }}
                                    label={item.label}
                                    config={item.config}
                                ></CustomSlider>
                            ) : item.type === 'imageReference' ? (
                                <ImgReference value={item.value}></ImgReference>
                            ) : item.type === 'controller' ? (
                                <Controller
                                    refreshParams={refershGroundParams}
                                    sdControllers={item.options}
                                ></Controller>
                            ) : item.type === 'aDetail' ? (
                                <ADetail
                                    loraOption={configs.find((it) => {
                                        return it.type === 'lora'
                                    })}
                                    refershLora={refershGroundParams}
                                ></ADetail>
                            ) : item.type === 'seed' ? (
                                <Seed></Seed>
                            ) : item.type === 'hiresFix' ? (
                                <HiresFix sdkey={item.key}></HiresFix>
                            ) : null}
                        </div>
                    </>
                )
            })}
        </div>
    )
}

export default SDImg
