import CustomSelect from '@/components/CustomSelect'
import { useTranslation } from 'next-i18next'
import { useEffect, useState } from 'react'
import { getControllerModels } from '@/pages/api/base'

interface IProp {
    settings: controllerSettings
    settingsChange: (settings: controllerSettings) => void
}

interface controllerSettings {
    [key: string]: any
}

const MODEL_KEY = 'model'

const ControllerModel = ({ settings, settingsChange }: IProp) => {
    const { t } = useTranslation('studio')

    const [models, setModels] = useState<string[]>([])

    const getModels = async (id: string, refresh: boolean) => {
        const data = await getControllerModels({ id, refresh })
        if (settings.id === id) {
            setModels(data ?? [])
            if (data?.length && (!settings[MODEL_KEY] || !data.includes(settings[MODEL_KEY]))) {
                handleChange(MODEL_KEY, data[0])
            }
        }
    }

    useEffect(() => {
        getModels(settings.id, false)
        // 这个依赖的是module，是因为上一层空间有个接口请求时间差的问题
    }, [settings.module])

    const handleChange = (key: string, value: number | string | boolean | null) => {
        settingsChange({
            ...settings,
            [key]: value,
        })
    }

    return (
        <CustomSelect
            value={settings[MODEL_KEY]}
            onChange={(value) => {
                handleChange(MODEL_KEY, value)
            }}
            label={t('sd.controlNetModel')}
            options={models.map((it) => {
                return {
                    label: it,
                    value: it,
                }
            })}
            refersh={() => {
                getModels(settings.id, true)
            }}
        ></CustomSelect>
    )
}

export default ControllerModel
