import { useEffect, useState } from 'react';
import { Button, Collapse, Form, Input, Select, Typography, message } from 'antd';
import type {
  DevPlanSettingsDto,
  KnowledgeBaseOptionDto,
  LlmApiConfigOptionDto,
} from '@dukang/shared-types';
import { request } from '../lib/api';

export default function DevPlanSettingsPage() {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [llmOptions, setLlmOptions] = useState<LlmApiConfigOptionDto[]>([]);
  const [kbOptions, setKbOptions] = useState<KnowledgeBaseOptionDto[]>([]);
  const [settingsForm] = Form.useForm();

  async function loadAll() {
    setLoading(true);
    try {
      const [s, llm, kb] = await Promise.all([
        request<DevPlanSettingsDto>('/admin/dev-plan/settings'),
        request<LlmApiConfigOptionDto[]>('/admin/llm-configs/options'),
        request<KnowledgeBaseOptionDto[]>('/admin/knowledge-bases/options'),
      ]);
      setLlmOptions(llm);
      setKbOptions(kb);
      settingsForm.setFieldsValue({
        reviewAssistantLlmConfigId: s.reviewAssistantLlmConfigId,
        reviewAssistantKnowledgeBaseId: s.reviewAssistantKnowledgeBaseId,
        reviewAssistantPrompt: s.reviewAssistantPrompt,
      });
    } catch (e) {
      message.error(e instanceof Error ? e.message : '加载失败');
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void loadAll();
  }, []);

  async function saveSettings() {
    const values = await settingsForm.validateFields();
    setSaving(true);
    try {
      await request<DevPlanSettingsDto>('/admin/dev-plan/settings', {
        method: 'PUT',
        body: JSON.stringify(values),
      });
      message.success('设置已保存');
    } catch (e) {
      message.error(e instanceof Error ? e.message : '保存失败');
    } finally {
      setSaving(false);
    }
  }

  return (
    <div>
      <Typography.Title level={4}>开发计划 · 开发设置</Typography.Title>
      <Typography.Paragraph type="secondary">
        任务评审派发 Webhook 已迁移至「企微机器人 → 消息推送」，勾选「开发任务评审派发」条件即可。
      </Typography.Paragraph>

      <Collapse
        defaultActiveKey={['review-ai']}
        style={{ marginTop: 16 }}
        items={[
          {
            key: 'review-ai',
            label: '本地审核 AI 助手',
            children: (
              <Form form={settingsForm} layout="vertical" disabled={loading}>
                <Typography.Paragraph type="secondary">
                  仅用于技术支持批量预审（只读知识库 + LLM），preview 阶段不写库。
                </Typography.Paragraph>
                <Form.Item name="reviewAssistantLlmConfigId" label="语言模型">
                  <Select
                    allowClear
                    options={llmOptions.map((o) => ({ value: o.id, label: o.name }))}
                  />
                </Form.Item>
                <Form.Item name="reviewAssistantKnowledgeBaseId" label="知识库">
                  <Select
                    allowClear
                    options={kbOptions.map((o) => ({ value: o.id, label: o.name }))}
                  />
                </Form.Item>
                <Form.Item name="reviewAssistantPrompt" label="审核提示词">
                  <Input.TextArea rows={5} />
                </Form.Item>
                <Button type="primary" loading={saving} onClick={() => void saveSettings()}>
                  保存
                </Button>
              </Form>
            ),
          },
        ]}
      />
    </div>
  );
}
