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) => 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 {
        // 新增模式：重置表单并设置默认providerId
        form.reset();
        form.setFieldsValue({
          providerId,
          enabled: true
        });
      }
    }
  }, [open, model, providerId]); // 移除form依赖，避免循环

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

  return (
    <Dialog
      header={isEdit ? '编辑模型' : '添加模型'}
      visible={open}
      onConfirm={() => { form?.submit(); return false; }}
      onClose={onCancel}
      confirmLoading={loading}
      confirmBtn="保存"
      cancelBtn="取消"
      destroyOnClose
    >
      <Form form={form} layout="vertical" onSubmit={handleSubmit}>
        {isEdit && model?.unifiedId && (
          <Form.FormItem label="统一模型 ID">
            <Input value={model.unifiedId} disabled />
            <div style={{ color: '#999', fontSize: 12, marginTop: 4 }}>
              格式：provider_id/model_name
            </div>
          </Form.FormItem>
        )}

        <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>
  );
}
