import { useEffect, useState, useCallback } from 'react';
import {
  Card,
  Form,
  Input,
  InputNumber,
  Button,
  Space,
  message,
  Divider,
  Spin,
  Tabs,
  Select,
  Switch,
  Collapse,
  Typography,
} from 'antd';
import { SaveOutlined, UndoOutlined } from '@ant-design/icons';
import { aiConfigApi, type AiConfig, type AiProviderConfig } from '../../api/ai/config';
import { AuthButton } from '../../components/AuthButton';
import { useThemeMode } from '../../hooks/useThemeMode';

const { TextArea } = Input;
const { Text } = Typography;

const PROVIDER_LABELS: Record<string, string> = {
  claude: 'Claude (Anthropic)',
  openai: 'OpenAI 兼容',
  ollama: 'Ollama (本地)',
};

export default function AiConfigPage() {
  const [config, setConfig] = useState<AiConfig | null>(null);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [form] = Form.useForm();
  const isDark = useThemeMode();

  const fetchConfig = useCallback(async () => {
    setLoading(true);
    try {
      const data = await aiConfigApi.get();
      setConfig(data);
      form.setFieldsValue({
        agentModel: data.agent.model,
        agentTemperature: data.agent.temperature,
        agentMaxTokens: data.agent.max_tokens,
        agentMaxIterations: data.agent.max_iterations,
        agentSystemPrompt: data.agent.system_prompt,
        analysisModel: data.analysis_defaults.model,
        analysisTemperature: data.analysis_defaults.temperature,
        analysisMaxTokens: data.analysis_defaults.max_tokens,
        defaultProvider: data.default_provider || 'claude',
        // Provider fields
        ...buildProviderFields(data.providers),
      });
    } catch {
      message.error('加载 AI 配置失败');
    } finally {
      setLoading(false);
    }
  }, [form]);

  useEffect(() => {
    fetchConfig();
  }, [fetchConfig]);

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setSaving(true);

      const providers: Record<string, AiProviderConfig> = {};
      for (const name of ['claude', 'openai', 'ollama']) {
        providers[name] = {
          provider_type: name,
          enabled: values[`provider_${name}_enabled`] ?? false,
          base_url: values[`provider_${name}_base_url`] ?? '',
          api_key: values[`provider_${name}_api_key`] ?? '',
          model: values[`provider_${name}_model`] ?? '',
        };
      }

      const updated: AiConfig = {
        agent: {
          model: values.agentModel,
          temperature: values.agentTemperature,
          max_tokens: values.agentMaxTokens,
          max_iterations: values.agentMaxIterations,
          system_prompt: values.agentSystemPrompt,
        },
        analysis_defaults: {
          model: values.analysisModel,
          temperature: values.analysisTemperature,
          max_tokens: values.analysisMaxTokens,
        },
        default_provider: values.defaultProvider || 'claude',
        providers,
      };

      const result = await aiConfigApi.update(updated);
      setConfig(result);
      message.success('AI 配置已保存');
    } catch (err: unknown) {
      if (err && typeof err === 'object' && 'errorFields' in err) {
        return;
      }
      message.error('保存 AI 配置失败');
    } finally {
      setSaving(false);
    }
  };

  const handleReset = async () => {
    try {
      const defaults = await aiConfigApi.getDefaults();
      form.setFieldsValue({
        agentModel: defaults.agent.model,
        agentTemperature: defaults.agent.temperature,
        agentMaxTokens: defaults.agent.max_tokens,
        agentMaxIterations: defaults.agent.max_iterations,
        agentSystemPrompt: defaults.agent.system_prompt,
        analysisModel: defaults.analysis_defaults.model,
        analysisTemperature: defaults.analysis_defaults.temperature,
        analysisMaxTokens: defaults.analysis_defaults.max_tokens,
      });
      message.info('已恢复为系统默认值（未保存）');
    } catch {
      message.error('加载默认配置失败');
    }
  };

  if (loading && !config) {
    return (
      <div style={{ textAlign: 'center', padding: 48 }}>
        <Spin size="large" />
      </div>
    );
  }

  const cardStyle = isDark
    ? { background: '#1f1f1f', borderColor: '#333' }
    : {};

  return (
    <div style={{ padding: 24, maxWidth: 960, margin: '0 auto' }}>
      <h2 style={{ marginBottom: 24 }}>AI 配置管理</h2>

      <Form form={form} layout="vertical">
        <Tabs
          items={[
            {
              key: 'agent',
              label: 'Agent 对话配置',
              forceRender: true,
              children: (
                <Card
                  title="AI 客服 Agent 参数"
                  size="small"
                  style={cardStyle}
                >
                  <Form.Item
                    label="模型名称"
                    name="agentModel"
                    rules={[{ required: true, message: '请输入模型名称' }]}
                    extra="如 claude-sonnet-4-6、gpt-4o 等"
                  >
                    <Input placeholder="claude-sonnet-4-6" />
                  </Form.Item>

                  <Space style={{ width: '100%' }} size="large">
                    <Form.Item
                      label="温度 (Temperature)"
                      name="agentTemperature"
                      rules={[{ required: true, message: '请输入温度参数' }]}
                      extra="0.0 ~ 2.0，越高越随机"
                      style={{ width: 200 }}
                    >
                      <InputNumber
                        min={0}
                        max={2}
                        step={0.1}
                        style={{ width: '100%' }}
                      />
                    </Form.Item>

                    <Form.Item
                      label="最大 Token"
                      name="agentMaxTokens"
                      rules={[{ required: true, message: '请输入最大 Token' }]}
                      extra="1 ~ 65536"
                      style={{ width: 200 }}
                    >
                      <InputNumber
                        min={1}
                        max={65536}
                        step={256}
                        style={{ width: '100%' }}
                      />
                    </Form.Item>

                    <Form.Item
                      label="最大迭代次数"
                      name="agentMaxIterations"
                      rules={[
                        { required: true, message: '请输入最大迭代次数' },
                      ]}
                      extra="1 ~ 20，Agent ReAct 循环上限"
                      style={{ width: 200 }}
                    >
                      <InputNumber
                        min={1}
                        max={20}
                        style={{ width: '100%' }}
                      />
                    </Form.Item>
                  </Space>

                  <Divider style={{ margin: '8px 0 16px' }} />

                  <Form.Item
                    label="系统提示词 (System Prompt)"
                    name="agentSystemPrompt"
                    rules={[{ required: true, message: '请输入系统提示词' }]}
                    extra="定义 AI 客服的角色和行为策略"
                  >
                    <TextArea rows={12} placeholder="你是 HMS 健康管理平台的 AI 健康顾问..." />
                  </Form.Item>
                </Card>
              ),
            },
            {
              key: 'analysis',
              label: '分析任务默认配置',
              forceRender: true,
              children: (
                <Card
                  title="AI 分析任务默认参数"
                  size="small"
                  style={cardStyle}
                  extra="当 Prompt 模板未指定模型参数时使用的默认值"
                >
                  <Form.Item
                    label="默认模型"
                    name="analysisModel"
                    rules={[{ required: true, message: '请输入默认模型' }]}
                    extra="化验单解读、趋势分析等分析任务的默认模型"
                  >
                    <Input placeholder="claude-sonnet-4-6" />
                  </Form.Item>

                  <Space style={{ width: '100%' }} size="large">
                    <Form.Item
                      label="默认温度"
                      name="analysisTemperature"
                      rules={[{ required: true, message: '请输入默认温度' }]}
                      extra="分析任务建议用较低温度"
                      style={{ width: 200 }}
                    >
                      <InputNumber
                        min={0}
                        max={2}
                        step={0.1}
                        style={{ width: '100%' }}
                      />
                    </Form.Item>

                    <Form.Item
                      label="默认最大 Token"
                      name="analysisMaxTokens"
                      rules={[
                        { required: true, message: '请输入默认最大 Token' },
                      ]}
                      style={{ width: 200 }}
                    >
                      <InputNumber
                        min={1}
                        max={65536}
                        step={256}
                        style={{ width: '100%' }}
                      />
                    </Form.Item>
                  </Space>
                </Card>
              ),
            },
            {
              key: 'providers',
              label: '模型供应商配置',
              forceRender: true,
              children: (
                <Card
                  title="AI 模型供应商"
                  size="small"
                  style={cardStyle}
                  extra="配置各 AI 供应商的连接参数，保存后立即生效"
                >
                  <Form.Item
                    label="默认供应商"
                    name="defaultProvider"
                    extra="系统优先使用的 AI 供应商"
                  >
                    <Select style={{ width: 240 }}>
                      <Select.Option value="claude">Claude (Anthropic)</Select.Option>
                      <Select.Option value="openai">OpenAI 兼容</Select.Option>
                      <Select.Option value="ollama">Ollama (本地)</Select.Option>
                    </Select>
                  </Form.Item>

                  <Divider style={{ margin: '8px 0 16px' }} />

                  <Collapse
                    items={(['claude', 'openai', 'ollama'] as const).map((name) => ({
                      key: name,
                      forceRender: true,
                      label: (
                        <Space>
                          <Form.Item
                            name={`provider_${name}_enabled`}
                            valuePropName="checked"
                            noStyle
                          >
                            <Switch size="small" />
                          </Form.Item>
                          <span>{PROVIDER_LABELS[name]}</span>
                          {config?.providers?.[name]?.enabled && (
                            <Text type="success">已启用</Text>
                          )}
                        </Space>
                      ),
                      children: (
                        <>
                          <Form.Item
                            label="Base URL"
                            name={`provider_${name}_base_url`}
                          >
                            <Input placeholder={
                              name === 'claude' ? 'https://api.anthropic.com' :
                              name === 'openai' ? 'https://api.openai.com' :
                              'http://localhost:11434'
                            } />
                          </Form.Item>

                          {name !== 'ollama' && (
                            <Form.Item
                              label="API Key"
                              name={`provider_${name}_api_key`}
                              extra="已保存的 Key 会显示为掩码格式（****xxxx），输入新值即可覆盖"
                            >
                              <Input.Password
                                placeholder="sk-..."
                                visibilityToggle
                              />
                            </Form.Item>
                          )}

                          <Form.Item
                            label="默认模型"
                            name={`provider_${name}_model`}
                          >
                            <Input placeholder={
                              name === 'claude' ? 'claude-sonnet-4-6' :
                              name === 'openai' ? 'gpt-4o' :
                              'qwen3:8b'
                            } />
                          </Form.Item>
                        </>
                      ),
                    }))}
                  />
                </Card>
              ),
            },
          ]}
        />

        <div style={{ marginTop: 16, textAlign: 'right' }}>
          <Space>
            <Button icon={<UndoOutlined />} onClick={handleReset}>
              恢复默认值
            </Button>
            <AuthButton code="ai.config.manage">
              <Button
                type="primary"
                icon={<SaveOutlined />}
                loading={saving}
                onClick={handleSave}
              >
                保存配置
              </Button>
            </AuthButton>
          </Space>
        </div>
      </Form>
    </div>
  );
}

const PROVIDER_DEFAULTS: Record<string, { base_url: string; model: string }> = {
  claude: { base_url: 'https://api.anthropic.com', model: 'claude-sonnet-4-6' },
  openai: { base_url: 'https://api.openai.com', model: 'gpt-4o' },
  ollama: { base_url: 'http://localhost:11434', model: 'qwen3:8b' },
};

function buildProviderFields(
  providers: Record<string, AiProviderConfig> | undefined,
): Record<string, unknown> {
  if (!providers) return {};
  const fields: Record<string, unknown> = {};
  for (const [name, cfg] of Object.entries(providers)) {
    const defaults = PROVIDER_DEFAULTS[name];
    fields[`provider_${name}_enabled`] = cfg.enabled;
    fields[`provider_${name}_base_url`] = cfg.base_url || defaults?.base_url || '';
    fields[`provider_${name}_api_key`] = cfg.api_key;
    fields[`provider_${name}_model`] = cfg.model || defaults?.model || '';
  }
  return fields;
}
