/**
 * [FE-AIAUTO-001] 自动化配置页面
 * 管理AI决策自动执行的配置、阈值和等级
 */

import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Row,
  Col,
  Statistic,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Switch,
  Tabs,
  Tooltip,
  Progress,
  Badge,
  message,
  Descriptions,
  Divider,
  Alert,
  Timeline,
  Popconfirm,
} from 'antd';
import {
  SettingOutlined,
  ThunderboltOutlined,
  SafetyOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  RiseOutlined,
  FallOutlined,
  HistoryOutlined,
  InfoCircleOutlined,
  SyncOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {
  autoExecutionDataSource,
  AutoExecutionConfig,
  LevelEvolutionRecord,
  AutomationLevel,
  DecisionModule,
  MODULE_NAMES,
  LEVEL_CAPABILITIES,
} from '@/services/autoExecutionDataSource';
import ThresholdConfigForm from './components/ThresholdConfigForm';
import EvolutionStage from './components/EvolutionStage';

const { Option } = Select;
const { TabPane } = Tabs;
const { TextArea } = Input;

const LEVEL_COLORS: Record<AutomationLevel, string> = {
  L1: 'default',
  L2: 'processing',
  L3: 'success',
  L4: 'warning',
};

const STATUS_COLORS: Record<string, string> = {
  ACTIVE: 'success',
  INACTIVE: 'default',
  SUSPENDED: 'error',
};

const AutoExecutionConfigPage: React.FC = () => {
  const [configs, setConfigs] = useState<AutoExecutionConfig[]>([]);
  const [evolutionHistory, setEvolutionHistory] = useState<LevelEvolutionRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedConfig, setSelectedConfig] = useState<AutoExecutionConfig | null>(null);
  const [configModalVisible, setConfigModalVisible] = useState(false);
  const [levelModalVisible, setLevelModalVisible] = useState(false);
  const [levelAction, setLevelAction] = useState<'upgrade' | 'downgrade'>('upgrade');
  const [levelForm] = Form.useForm();

  useEffect(() => {
    fetchConfigs();
    fetchHistory();
  }, []);

  const fetchConfigs = async () => {
    setLoading(true);
    try {
      const data = await autoExecutionDataSource.fetchConfigs('tenant-001');
      setConfigs(data);
    } catch (error) {
      message.error('获取配置失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchHistory = async () => {
    try {
      const data = await autoExecutionDataSource.fetchEvolutionHistory('tenant-001');
      setEvolutionHistory(data);
    } catch (error) {
      console.error('获取演进历史失败', error);
    }
  };

  const handleUpdateConfig = async (values: Partial<AutoExecutionConfig>) => {
    if (!selectedConfig) return;
    try {
      await autoExecutionDataSource.updateConfig(selectedConfig.id, values);
      message.success('配置更新成功');
      setConfigModalVisible(false);
      fetchConfigs();
    } catch (error) {
      message.error('配置更新失败');
    }
  };

  const handleLevelChange = async (values: { reason: string }) => {
    if (!selectedConfig) return;
    try {
      const targetLevel = levelAction === 'upgrade'
        ? getNextLevel(selectedConfig.automation_level)
        : getPrevLevel(selectedConfig.automation_level);

      if (levelAction === 'upgrade') {
        await autoExecutionDataSource.upgradeLevel(
          selectedConfig.tenant_id,
          selectedConfig.shop_id,
          selectedConfig.module,
          targetLevel,
          values.reason
        );
        message.success(`等级已升级至 ${targetLevel}`);
      } else {
        await autoExecutionDataSource.downgradeLevel(
          selectedConfig.tenant_id,
          selectedConfig.shop_id,
          selectedConfig.module,
          targetLevel,
          values.reason
        );
        message.success(`等级已降级至 ${targetLevel}`);
      }
      setLevelModalVisible(false);
      levelForm.resetFields();
      fetchConfigs();
      fetchHistory();
    } catch (error: any) {
      message.error(error.message || '等级变更失败');
    }
  };

  const getNextLevel = (current: AutomationLevel): AutomationLevel => {
    const levels: AutomationLevel[] = ['L1', 'L2', 'L3', 'L4'];
    const index = levels.indexOf(current);
    return levels[Math.min(index + 1, 3)];
  };

  const getPrevLevel = (current: AutomationLevel): AutomationLevel => {
    const levels: AutomationLevel[] = ['L1', 'L2', 'L3', 'L4'];
    const index = levels.indexOf(current);
    return levels[Math.max(index - 1, 0)];
  };

  const canUpgrade = (config: AutoExecutionConfig): boolean => {
    if (config.automation_level === 'L4') return false;
    const stats = config.statistics;
    if (stats.total_executions < 100) return false;
    const successRate = stats.success_count / stats.total_executions;
    return successRate >= 0.95;
  };

  const columns: ColumnsType<AutoExecutionConfig> = [
    {
      title: '模块',
      dataIndex: 'module',
      key: 'module',
      render: (module: DecisionModule) => (
        <Tag color="blue">{MODULE_NAMES[module]}</Tag>
      ),
    },
    {
      title: '自动化等级',
      dataIndex: 'automation_level',
      key: 'automation_level',
      render: (level: AutomationLevel) => (
        <Tag color={LEVEL_COLORS[level]}>{level}</Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Badge status={STATUS_COLORS[status] as any} text={status} />
      ),
    },
    {
      title: '置信度阈值',
      key: 'thresholds',
      render: (_, record) => (
        <Space direction="vertical" size="small">
          <span>自动执行: {(record.confidence_thresholds.auto_execute * 100).toFixed(0)}%</span>
          <span>待审核: {(record.confidence_thresholds.pending_review * 100).toFixed(0)}%</span>
        </Space>
      ),
    },
    {
      title: '执行统计',
      key: 'statistics',
      render: (_, record) => {
        const stats = record.statistics;
        const successRate = stats.total_executions > 0 
          ? ((stats.success_count / stats.total_executions) * 100).toFixed(1)
          : '0';
        return (
          <Space direction="vertical" size="small">
            <span>总执行: {stats.total_executions} 次</span>
            <Progress 
              percent={parseFloat(successRate)} 
              size="small" 
              status={parseFloat(successRate) >= 95 ? 'success' : 'normal'}
              format={() => `成功率: ${successRate}%`}
            />
          </Space>
        );
      },
    },
    {
      title: '平均置信度',
      dataIndex: ['statistics', 'avg_confidence'],
      key: 'avg_confidence',
      render: (confidence: number) => (
        <Progress 
          percent={confidence * 100} 
          size="small" 
          format={(percent) => `${percent?.toFixed(1)}%`}
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Tooltip title="配置阈值">
            <Button
              type="link"
              icon={<SettingOutlined />}
              onClick={() => {
                setSelectedConfig(record);
                setConfigModalVisible(true);
              }}
            />
          </Tooltip>
          {record.automation_level !== 'L4' && (
            <Tooltip title={canUpgrade(record) ? '升级等级' : '升级条件未满足（需100次执行且95%成功率）'}>
              <Button
                type="link"
                icon={<RiseOutlined />}
                disabled={!canUpgrade(record)}
                onClick={() => {
                  setSelectedConfig(record);
                  setLevelAction('upgrade');
                  setLevelModalVisible(true);
                }}
              />
            </Tooltip>
          )}
          {record.automation_level !== 'L1' && (
            <Tooltip title="降级等级">
              <Button
                type="link"
                icon={<FallOutlined />}
                danger
                onClick={() => {
                  setSelectedConfig(record);
                  setLevelAction('downgrade');
                  setLevelModalVisible(true);
                }}
              />
            </Tooltip>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div className="auto-execution-config-page">
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Alert
            message="AI决策自动化配置"
            description="管理各模块的自动化等级和执行阈值。等级越高，自动执行范围越广，但需要满足严格的成功率要求。"
            type="info"
            showIcon
            icon={<ThunderboltOutlined />}
          />
        </Col>

        <Col span={24}>
          <EvolutionStage />
        </Col>

        <Col span={24}>
          <Card title="模块配置列表" extra={
            <Button icon={<SyncOutlined />} onClick={fetchConfigs}>刷新</Button>
          }>
            <Table
              columns={columns}
              dataSource={configs}
              rowKey="id"
              loading={loading}
              pagination={false}
            />
          </Card>
        </Col>

        <Col span={24}>
          <Card title="等级演进历史" extra={<HistoryOutlined />}>
            {evolutionHistory.length > 0 ? (
              <Timeline
                items={evolutionHistory.slice(0, 10).map(record => ({
                  color: record.to_level > record.from_level ? 'green' : 'red',
                  children: (
                    <div>
                      <p>
                        <Tag color="blue">{MODULE_NAMES[record.module]}</Tag>
                        <Tag>{record.from_level}</Tag>
                        <RiseOutlined style={{ margin: '0 8px' }} />
                        <Tag color="green">{record.to_level}</Tag>
                      </p>
                      <p>原因: {record.reason}</p>
                      <p>
                        <small>
                          成功率: {(record.metrics.success_rate * 100).toFixed(1)}% | 
                          执行次数: {record.metrics.total_executions} |
                          审批人: {record.approved_by} |
                          时间: {new Date(record.created_at).toLocaleString()}
                        </small>
                      </p>
                    </div>
                  ),
                }))}
              />
            ) : (
              <div style={{ textAlign: 'center', color: '#999', padding: '20px' }}>
                暂无演进记录
              </div>
            )}
          </Card>
        </Col>
      </Row>

      <Modal
        title={`配置阈值 - ${selectedConfig ? MODULE_NAMES[selectedConfig.module] : ''}`}
        open={configModalVisible}
        onCancel={() => setConfigModalVisible(false)}
        footer={null}
        width={700}
      >
        {selectedConfig && (
          <ThresholdConfigForm
            config={selectedConfig}
            onSubmit={handleUpdateConfig}
            onCancel={() => setConfigModalVisible(false)}
          />
        )}
      </Modal>

      <Modal
        title={`${levelAction === 'upgrade' ? '升级' : '降级'}自动化等级`}
        open={levelModalVisible}
        onCancel={() => {
          setLevelModalVisible(false);
          levelForm.resetFields();
        }}
        onOk={() => levelForm.submit()}
      >
        {selectedConfig && (
          <>
            <Alert
              message={`当前等级: ${selectedConfig.automation_level} → 目标等级: ${levelAction === 'upgrade' ? getNextLevel(selectedConfig.automation_level) : getPrevLevel(selectedConfig.automation_level)}`}
              type={levelAction === 'upgrade' ? 'success' : 'warning'}
              showIcon
              style={{ marginBottom: 16 }}
            />
            <Descriptions column={1} bordered size="small">
              <Descriptions.Item label="模块">{MODULE_NAMES[selectedConfig.module]}</Descriptions.Item>
              <Descriptions.Item label="总执行次数">{selectedConfig.statistics.total_executions}</Descriptions.Item>
              <Descriptions.Item label="成功率">
                {selectedConfig.statistics.total_executions > 0 
                  ? ((selectedConfig.statistics.success_count / selectedConfig.statistics.total_executions) * 100).toFixed(1) + '%'
                  : 'N/A'}
              </Descriptions.Item>
            </Descriptions>
            <Divider />
            <Form form={levelForm} layout="vertical" onFinish={handleLevelChange}>
              <Form.Item
                name="reason"
                label="变更原因"
                rules={[{ required: true, message: '请输入变更原因' }]}
              >
                <TextArea rows={3} placeholder="请说明等级变更的原因..." />
              </Form.Item>
            </Form>
          </>
        )}
      </Modal>
    </div>
  );
};

export default AutoExecutionConfigPage;
