import { Form, Input, Modal, Select } from 'antd';
import type { FormInstance } from 'antd';
import type { LLMProvider } from '../../../api';
import { KIND_OPTIONS } from '../constants';

export default function ProviderEditorModal(props: {
  open: boolean;
  editing: LLMProvider | null;
  form: FormInstance;
  onCancel: () => void;
  onOk: () => void;
}) {
  const { open, editing, form, onCancel, onOk } = props;

  return (
    <Modal
      open={open}
      title={editing ? '编辑 Provider' : '添加 Provider'}
      onCancel={onCancel}
      onOk={onOk}
      width={600}
      okText="保存"
      cancelText="取消"
      destroyOnHidden
    >
      <Form
        form={form}
        layout="vertical"
        onValuesChange={(changed) => {
          if (changed.kind) {
            const opt = KIND_OPTIONS.find((o) => o.value === changed.kind);
            if (opt?.baseUrl && !form.getFieldValue('baseUrl')) {
              form.setFieldsValue({ baseUrl: opt.baseUrl });
            }
          }
        }}
      >
        <Form.Item name="name" label="名称" rules={[{ required: true }]}>
          <Input placeholder="例如：我的 OpenAI" />
        </Form.Item>
        <Form.Item name="kind" label="类型" rules={[{ required: true }]}>
          <Select>
            {KIND_OPTIONS.map((k) => (
              <Select.Option key={k.value} value={k.value}>
                {k.label}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          name="baseUrl"
          label="Base URL"
          rules={[{ required: true }]}
          tooltip={KIND_OPTIONS.find((k) => k.value === form.getFieldValue('kind'))?.hint}
        >
          <Input placeholder="https://api.openai.com/v1" />
        </Form.Item>
        <Form.Item name="apiKey" label={editing ? 'API Key（留空保留原值）' : 'API Key'} rules={editing ? [] : [{ required: true }]}>
          <Input.Password placeholder="sk-..." autoComplete="new-password" />
        </Form.Item>
        <Form.Item name="models" label="可用模型（逗号分隔）" tooltip="用于在 agent 编辑器中下拉选择">
          <Input placeholder="gpt-4o, gpt-4o-mini" />
        </Form.Item>
        <Form.Item name="defaultModel" label="默认模型">
          <Input placeholder="例如 gpt-4o-mini" />
        </Form.Item>
      </Form>
    </Modal>
  );
}

