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

interface ProviderFormValues {
  id: string;
  name: string;
  apiKey: string;
  baseUrl: string;
  enabled: boolean;
}

interface ProviderFormProps {
  open: boolean;
  provider?: Provider;
  onSave: (values: ProviderFormValues) => void;
  onCancel: () => void;
  loading: boolean;
}

export function ProviderForm({
  open,
  provider,
  onSave,
  onCancel,
  loading,
}: ProviderFormProps) {
  const [form] = Form.useForm();
  const isEdit = !!provider;

  // 当弹窗打开或provider变化时，设置表单值
  useEffect(() => {
    if (open && form) {
      if (provider) {
        // 编辑模式：设置现有值
        form.setFieldsValue({
          id: provider.id,
          name: provider.name,
          apiKey: '',
          baseUrl: provider.baseUrl,
          enabled: provider.enabled,
        });
      } else {
        // 新增模式：重置表单
        form.reset();
        form.setFieldsValue({ enabled: true });
      }
    }
  }, [open, provider]); // 移除form依赖，避免循环

  const handleSubmit = (context: SubmitContext) => {
    if (context.validateResult === true && form) {
      const values = form.getFieldsValue(true) as ProviderFormValues;
      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}>
        <Form.FormItem label="ID" name="id" rules={[{ required: true, message: '请输入供应商 ID' }]}>
          <Input disabled={isEdit} placeholder="例如: openai" />
        </Form.FormItem>

        <Form.FormItem label="名称" name="name" rules={[{ required: true, message: '请输入名称' }]}>
          <Input placeholder="例如: OpenAI" />
        </Form.FormItem>

        <Form.FormItem
          label={isEdit ? 'API Key（留空则不修改）' : 'API Key'}
          name="apiKey"
          rules={isEdit ? [] : [{ required: true, message: '请输入 API Key' }]}
        >
          <Input type="password" placeholder="sk-..." autocomplete="current-password" />
        </Form.FormItem>

        <Form.FormItem
          label="Base URL"
          name="baseUrl"
          rules={[
            { required: true, message: '请输入 Base URL' },
            { url: true, message: '请输入有效的 URL' },
          ]}
        >
          <Input placeholder="例如: https://api.openai.com/v1" />
        </Form.FormItem>

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