import { useEffect } from 'react'
import { Dialog, Form, Input, Select, Switch } from 'tdesign-react'
import type { Provider, Model } from '@/types'
import type { SubmitContext } from 'tdesign-react/es/form/type'

interface ModelFormValues {
  providerId: string
  modelName: string
  enabled: boolean
}

interface ModelFormProps {
  open: boolean
  model?: Model
  providerId: string
  providers: Provider[]
  onSave: (values: ModelFormValues) => Promise<void> | void
  onCancel: () => void
  loading: boolean
}

export function ModelForm({ open, model, providerId, providers, onSave, onCancel, loading }: ModelFormProps) {
  const [form] = Form.useForm()
  const isEdit = !!model

  // 当弹窗打开或 model 变化时，同步表单初始值。
  useEffect(() => {
    if (open && form) {
      if (model) {
        form.setFieldsValue({
          providerId: model.providerId,
          modelName: model.modelName,
          enabled: model.enabled,
        })
      } else {
        form.reset()
        form.setFieldsValue({
          providerId,
          enabled: true,
        })
      }
    }
  }, [form, open, model, providerId])

  const handleSubmit = (context: SubmitContext) => {
    if (context.validateResult === true && form) {
      const values = form.getFieldsValue(true) as ModelFormValues
      onSave(values)
    }
  }

  return (
    <Dialog
      header={isEdit ? '编辑模型' : '添加模型'}
      visible={open}
      placement='center'
      width='520px'
      closeOnOverlayClick={false}
      closeOnEscKeydown={false}
      lazy={false}
      onConfirm={() => {
        form?.submit()
        return false
      }}
      onClose={onCancel}
      confirmLoading={loading}
      confirmBtn='保存'
      cancelBtn='取消'
    >
      <Form form={form} layout='vertical' onSubmit={handleSubmit}>
        <Form.FormItem label='供应商' name='providerId' rules={[{ required: true, message: '请选择供应商' }]}>
          <Select options={providers.map((p) => ({ label: p.name, value: p.id }))} />
        </Form.FormItem>

        <Form.FormItem label='模型名称' name='modelName' rules={[{ required: true, message: '请输入模型名称' }]}>
          <Input placeholder='例如: gpt-4o' />
        </Form.FormItem>

        <Form.FormItem label='启用' name='enabled'>
          <Switch />
        </Form.FormItem>
      </Form>
    </Dialog>
  )
}
