/**
 * [FE-AIAUTO-002] 阈值配置表单组件
 * 用于配置自动执行的置信度阈值和风险限制
 */

import React from 'react';
import {
  Form,
  InputNumber,
  Select,
  Switch,
  Divider,
  Row,
  Col,
  Card,
  Slider,
  Space,
  Tag,
  Alert,
} from 'antd';
import {
  ThunderboltOutlined,
  SafetyOutlined,
  ClockCircleOutlined,
  BellOutlined,
} from '@ant-design/icons';
import { AutoExecutionConfig, RiskLevel, LEVEL_CAPABILITIES } from '@/services/autoExecutionDataSource';

const { Option } = Select;

interface ThresholdConfigFormProps {
  config: AutoExecutionConfig;
  onSubmit: (values: Partial<AutoExecutionConfig>) => void;
  onCancel: () => void;
}

const ThresholdConfigForm: React.FC<ThresholdConfigFormProps> = ({
  config,
  onSubmit,
  onCancel,
}) => {
  const [form] = Form.useForm();

  const handleSubmit = (values: any) => {
    const thresholds = {
      auto_execute: values.auto_execute / 100,
      pending_review: values.pending_review / 100,
      auto_reject: values.auto_reject / 100,
    };

    const riskLimits = {
      max_amount: values.max_amount,
      max_quantity: values.max_quantity,
      allowed_risk_levels: values.allowed_risk_levels,
    };

    const timeRestrictions = {
      allowed_hours: values.allowed_hours || Array.from({ length: 24 }, (_, i) => i),
      excluded_dates: config.time_restrictions.excluded_dates,
    };

    const rollbackConfig = {
      enabled: values.rollback_enabled,
      max_attempts: values.max_attempts,
      cooldown_minutes: values.cooldown_minutes,
    };

    const notificationConfig = {
      on_execute: values.notify_execute,
      on_fail: values.notify_fail,
      on_rollback: values.notify_rollback,
      channels: values.notification_channels,
    };

    onSubmit({
      confidence_thresholds: thresholds,
      risk_limits: riskLimits,
      time_restrictions: timeRestrictions,
      rollback_config: rollbackConfig,
      notification_config: notificationConfig,
    });
  };

  const levelCapability = LEVEL_CAPABILITIES[config.automation_level];
  const maxAmountLimit = config.risk_limits.max_amount * levelCapability.max_amount_multiplier;

  return (
    <Form
      form={form}
      layout="vertical"
      initialValues={{
        auto_execute: config.confidence_thresholds.auto_execute * 100,
        pending_review: config.confidence_thresholds.pending_review * 100,
        auto_reject: config.confidence_thresholds.auto_reject * 100,
        max_amount: config.risk_limits.max_amount,
        max_quantity: config.risk_limits.max_quantity,
        allowed_risk_levels: config.risk_limits.allowed_risk_levels,
        allowed_hours: config.time_restrictions.allowed_hours,
        rollback_enabled: config.rollback_config.enabled,
        max_attempts: config.rollback_config.max_attempts,
        cooldown_minutes: config.rollback_config.cooldown_minutes,
        notify_execute: config.notification_config.on_execute,
        notify_fail: config.notification_config.on_fail,
        notify_rollback: config.notification_config.on_rollback,
        notification_channels: config.notification_config.channels,
      }}
      onFinish={handleSubmit}
    >
      <Alert
        message={`当前等级: ${config.automation_level} - ${levelCapability.description}`}
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />

      <Card 
        title={<><ThunderboltOutlined /> 置信度阈值配置</>}
        size="small"
        style={{ marginBottom: 16 }}
      >
        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              name="auto_execute"
              label="自动执行阈值 (%)"
              tooltip="置信度达到此阈值时自动执行"
            >
              <Slider
                min={50}
                max={100}
                marks={{ 50: '50%', 75: '75%', 100: '100%' }}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="pending_review"
              label="待审核阈值 (%)"
              tooltip="置信度在此区间需要人工审核"
            >
              <Slider
                min={30}
                max={90}
                marks={{ 30: '30%', 60: '60%', 90: '90%' }}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="auto_reject"
              label="自动拒绝阈值 (%)"
              tooltip="置信度低于此阈值自动拒绝"
            >
              <Slider
                min={10}
                max={70}
                marks={{ 10: '10%', 40: '40%', 70: '70%' }}
              />
            </Form.Item>
          </Col>
        </Row>
      </Card>

      <Card
        title={<><SafetyOutlined /> 风险限制配置</>}
        size="small"
        style={{ marginBottom: 16 }}
      >
        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              name="max_amount"
              label="最大金额限制"
              tooltip={`当前等级最大允许: ${maxAmountLimit}`}
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                max={maxAmountLimit}
                prefix="¥"
                formatter={(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="max_quantity"
              label="最大数量限制"
            >
              <InputNumber
                style={{ width: '100%' }}
                min={1}
                max={10000}
              />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="allowed_risk_levels"
              label="允许的风险等级"
            >
              <Select mode="multiple" style={{ width: '100%' }}>
                <Option value="LOW">
                  <Tag color="green">LOW</Tag>
                </Option>
                <Option value="MEDIUM">
                  <Tag color="orange">MEDIUM</Tag>
                </Option>
                <Option value="HIGH" disabled={levelCapability.max_risk_level === 'LOW'}>
                  <Tag color="red">HIGH</Tag>
                </Option>
                <Option value="CRITICAL" disabled={levelCapability.max_risk_level !== 'CRITICAL'}>
                  <Tag color="purple">CRITICAL</Tag>
                </Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
      </Card>

      <Card
        title={<><ClockCircleOutlined /> 时间限制配置</>}
        size="small"
        style={{ marginBottom: 16 }}
      >
        <Form.Item
          name="allowed_hours"
          label="允许执行的时间段"
          tooltip="选择允许自动执行的小时（0-23）"
        >
          <Select mode="multiple" style={{ width: '100%' }}>
            {Array.from({ length: 24 }, (_, i) => (
              <Option key={i} value={i}>
                {i.toString().padStart(2, '0')}:00
              </Option>
            ))}
          </Select>
        </Form.Item>
      </Card>

      <Card
        title={<><ThunderboltOutlined /> 回滚配置</>}
        size="small"
        style={{ marginBottom: 16 }}
      >
        <Row gutter={16}>
          <Col span={6}>
            <Form.Item
              name="rollback_enabled"
              label="启用自动回滚"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>
          </Col>
          <Col span={9}>
            <Form.Item
              name="max_attempts"
              label="最大重试次数"
            >
              <InputNumber min={1} max={10} style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={9}>
            <Form.Item
              name="cooldown_minutes"
              label="冷却时间（分钟）"
            >
              <InputNumber min={1} max={1440} style={{ width: '100%' }} />
            </Form.Item>
          </Col>
        </Row>
      </Card>

      <Card
        title={<><BellOutlined /> 通知配置</>}
        size="small"
        style={{ marginBottom: 16 }}
      >
        <Row gutter={16}>
          <Col span={6}>
            <Form.Item
              name="notify_execute"
              label="执行时通知"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item
              name="notify_fail"
              label="失败时通知"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item
              name="notify_rollback"
              label="回滚时通知"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item
              name="notification_channels"
              label="通知渠道"
            >
              <Select mode="multiple" style={{ width: '100%' }}>
                <Option value="EMAIL">邮件</Option>
                <Option value="SMS">短信</Option>
                <Option value="WEBHOOK">Webhook</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
      </Card>

      <Divider />

      <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
        <button type="button" onClick={onCancel} className="ant-btn">
          取消
        </button>
        <button type="submit" className="ant-btn ant-btn-primary">
          保存配置
        </button>
      </Space>
    </Form>
  );
};

export default ThresholdConfigForm;
