/**
 * 证书管理页面
 * 使用DataSource抽象层获取数据，支持Mock/真实API自动切换
 * 
 * @module pages/Compliance/CertificateManage
 * @author AI-Frontend-Team
 * @created 2026-03-19
 */

import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  Upload,
  Descriptions,
  Divider,
  message,
  Tag,
  Tabs,
  Row,
  Col,
  Statistic,
  Alert,
  Tooltip,
  Badge,
} from 'antd';
import {
  FileTextOutlined,
  PlusOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  UploadOutlined,
  DownloadOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  CloseCircleOutlined,
  WarningOutlined,
  BellOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { certificateDataSource, __DATA_SOURCE_TYPE__ } from '@/services/certificateDataSource';
import { Certificate } from '@/types/certificate';

const { Option } = Select;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

// 证书类型映射
const CERT_TYPE_MAP: Record<string, { label: string; color: string }> = {
  PRODUCT_CERT: { label: '产品认证', color: 'blue' },
  BUSINESS_LICENSE: { label: '营业执照', color: 'green' },
  SAFETY_CERT: { label: '安全认证', color: 'red' },
  QUALITY_CERT: { label: '质量认证', color: 'purple' },
  OTHER: { label: '其他', color: 'default' },
};

// 状态映射
const STATUS_MAP: Record<string, { text: string; color: string; icon: React.ReactNode }> = {
  APPROVED: { text: '已批准', color: 'success', icon: <CheckCircleOutlined /> },
  PENDING: { text: '待审核', color: 'warning', icon: <ClockCircleOutlined /> },
  REJECTED: { text: '已拒绝', color: 'error', icon: <CloseCircleOutlined /> },
  EXPIRED: { text: '已过期', color: 'red', icon: <CloseCircleOutlined /> },
};

// 模拟产品列表（用于创建表单）
const MOCK_PRODUCTS = [
  { id: 'P001', name: '工业温度传感器' },
  { id: 'P002', name: '控制模块B' },
  { id: 'P003', name: '电源单元C' },
  { id: 'P004', name: '通信网关D' },
];

export const CertificateManage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [certificates, setCertificates] = useState<Certificate[]>([]);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedCert, setSelectedCert] = useState<Certificate | null>(null);
  const [activeTab, setActiveTab] = useState('all');

  // 组件挂载时加载数据
  useEffect(() => {
    fetchCertificates();
  }, []);

  /**
   * 获取证书列表
   * 通过DataSource抽象层获取数据
   */
  const fetchCertificates = async () => {
    setLoading(true);
    try {
      // 使用DataSource获取数据（自动切换Mock/真实API）
      const data = await certificateDataSource.list();
      setCertificates(data);
      
      if (__DATA_SOURCE_TYPE__ === 'mock') {
        console.log('[CertificateManage] Using mock data source');
      }
    } catch (error) {
      message.error('Failed to fetch certificates');
      console.error('[CertificateManage] Error fetching certificates:', error);
    } finally {
      setLoading(false);
    }
  };

  /**
   * 创建证书
   */
  const handleCreateCert = async (values: any) => {
    setLoading(true);
    try {
      const product = MOCK_PRODUCTS.find(p => p.id === values.productId);
      
      // 使用DataSource创建数据
      const newCert = await certificateDataSource.create({
        name: values.name,
        type: values.type,
        productId: values.productId,
        productName: product?.name,
        expiryDate: values.expiryDate?.format('YYYY-MM-DD'),
        notes: values.notes,
      });

      message.success('Certificate created successfully');
      setCreateModalVisible(false);
      form.resetFields();
      
      // 刷新列表
      await fetchCertificates();
    } catch (error) {
      message.error('Failed to create certificate');
      console.error('[CertificateManage] Error creating certificate:', error);
    } finally {
      setLoading(false);
    }
  };

  /**
   * 查看详情
   */
  const handleViewDetail = (cert: Certificate) => {
    setSelectedCert(cert);
    setDetailModalVisible(true);
  };

  /**
   * 更新证书状态（续期）
   */
  const handleRenew = async (cert: Certificate) => {
    Modal.confirm({
      title: '续期证书',
      content: `确定要为证书 ${cert.name} 发起续期申请吗？`,
      onOk: async () => {
        try {
          await certificateDataSource.update(cert.id, {
            status: 'PENDING',
          });
          message.success('续期申请已提交');
          await fetchCertificates();
        } catch (error) {
          message.error('Failed to renew certificate');
          console.error('[CertificateManage] Error renewing certificate:', error);
        }
      },
    });
  };

  /**
   * 删除证书
   */
  const handleDelete = async (certId: string) => {
    Modal.confirm({
      title: '删除证书',
      content: '确定要删除此证书吗？此操作不可恢复。',
      okType: 'danger',
      onOk: async () => {
        try {
          await certificateDataSource.delete(certId);
          message.success('证书已删除');
          await fetchCertificates();
        } catch (error) {
          message.error('Failed to delete certificate');
          console.error('[CertificateManage] Error deleting certificate:', error);
        }
      },
    });
  };

  /**
   * 获取过滤后的证书列表
   */
  const getFilteredCerts = () => {
    if (activeTab === 'all') return certificates;
    if (activeTab === 'expiring') {
      return certificates.filter(c => {
        if (!c.expiryDate) return false;
        const daysUntilExpiry = dayjs(c.expiryDate).diff(dayjs(), 'day');
        return daysUntilExpiry > 0 && daysUntilExpiry <= 90;
      });
    }
    return certificates.filter(c => c.status === activeTab.toUpperCase());
  };

  // 表格列定义
  const columns: ColumnsType<Certificate> = [
    {
      title: '证书名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      ellipsis: true,
      render: (name: string, record: Certificate) => (
        <a onClick={() => handleViewDetail(record)}>{name}</a>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type: string) => {
        const config = CERT_TYPE_MAP[type] || { label: type, color: 'default' };
        return <Tag color={config.color}>{config.label}</Tag>;
      },
    },
    {
      title: '关联产品',
      dataIndex: 'productName',
      key: 'productName',
      width: 160,
      render: (name: string) => name || '-',
    },
    {
      title: '到期日期',
      dataIndex: 'expiryDate',
      key: 'expiryDate',
      width: 120,
      render: (date: string) => {
        if (!date) return '-';
        const daysUntilExpiry = dayjs(date).diff(dayjs(), 'day');
        const isExpiringSoon = daysUntilExpiry > 0 && daysUntilExpiry <= 90;
        const isExpired = daysUntilExpiry <= 0;
        return (
          <Tooltip title={isExpiringSoon ? `${daysUntilExpiry}天后到期` : isExpired ? '已过期' : ''}>
            <span style={{ color: isExpiringSoon || isExpired ? '#ff4d4f' : undefined }}>
              {date}
            </span>
          </Tooltip>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const config = STATUS_MAP[status] || { text: status, color: 'default', icon: null };
        return <Tag color={config.color} icon={config.icon}>{config.text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      render: (_, record: Certificate) => (
        <Space>
          <Tooltip title="查看详情">
            <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)} />
          </Tooltip>
          {record.status === 'APPROVED' && (
            <Tooltip title="续期">
              <Button type="link" icon={<ClockCircleOutlined />} onClick={() => handleRenew(record)} />
            </Tooltip>
          )}
          <Tooltip title="删除">
            <Button type="link" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record.id)} />
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 统计数据
  const stats = {
    total: certificates.length,
    valid: certificates.filter(c => c.status === 'APPROVED').length,
    expiring: certificates.filter(c => {
      if (!c.expiryDate) return false;
      const days = dayjs(c.expiryDate).diff(dayjs(), 'day');
      return days > 0 && days <= 90;
    }).length,
    expired: certificates.filter(c => c.status === 'EXPIRED').length,
  };

  return (
    <div className="certificate-manage-page">
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={4}>
          <Card>
            <Statistic title="证书总数" value={stats.total} prefix={<FileTextOutlined />} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic title="有效" value={stats.valid} valueStyle={{ color: '#52c41a' }} prefix={<CheckCircleOutlined />} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic title="即将到期" value={stats.expiring} valueStyle={{ color: '#faad14' }} prefix={<WarningOutlined />} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic title="已过期" value={stats.expired} valueStyle={{ color: '#ff4d4f' }} prefix={<CloseCircleOutlined />} />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Alert
              message="证书到期提醒"
              description={`${stats.expiring} 个证书将在90天内到期，请及时处理。`}
              type="warning"
              showIcon
              icon={<BellOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 证书列表 */}
      <Card 
        title="证书管理" 
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateModalVisible(true)}>
            添加证书
          </Button>
        }
      >
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="全部" key="all" />
          <TabPane tab={<Badge count={stats.expiring} offset={[10, 0]} size="small">即将到期</Badge>} key="expiring" />
          <TabPane tab="有效" key="approved" />
          <TabPane tab="已过期" key="expired" />
          <TabPane tab="待审核" key="pending" />
        </Tabs>

        <Table
          columns={columns}
          dataSource={getFilteredCerts()}
          rowKey="id"
          loading={loading}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      {/* 创建证书弹窗 */}
      <Modal
        title="添加新证书"
        open={createModalVisible}
        onCancel={() => setCreateModalVisible(false)}
        footer={null}
        width={700}
      >
        <Form form={form} layout="vertical" onFinish={handleCreateCert}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="type" label="证书类型" rules={[{ required: true }]}>
                <Select placeholder="选择类型">
                  {Object.entries(CERT_TYPE_MAP).map(([key, config]) => (
                    <Option key={key} value={key}>{config.label}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="productId" label="关联产品">
                <Select placeholder="选择产品" allowClear>
                  {MOCK_PRODUCTS.map(p => (
                    <Option key={p.id} value={p.id}>{p.name}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="name" label="证书名称" rules={[{ required: true }]}>
            <Input placeholder="输入证书名称" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="expiryDate" label="到期日期" rules={[{ required: true }]}>
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="notes" label="备注">
            <Input.TextArea rows={3} placeholder="输入备注信息" />
          </Form.Item>

          <Form.Item name="attachments" label="附件">
            <Upload>
              <Button icon={<UploadOutlined />}>上传文件</Button>
            </Upload>
          </Form.Item>

          <div style={{ textAlign: 'right' }}>
            <Button onClick={() => setCreateModalVisible(false)} style={{ marginRight: 8 }}>取消</Button>
            <Button type="primary" htmlType="submit" loading={loading}>创建证书</Button>
          </div>
        </Form>
      </Modal>

      {/* 详情弹窗 */}
      <Modal
        title="证书详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>关闭</Button>,
          selectedCert?.status === 'APPROVED' && (
            <Button 
              key="renew" 
              type="primary" 
              icon={<ClockCircleOutlined />} 
              onClick={() => { handleRenew(selectedCert!); setDetailModalVisible(false); }}
            >
              申请续期
            </Button>
          ),
        ]}
        width={700}
      >
        {selectedCert && (
          <>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="证书ID">{selectedCert.id}</Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={STATUS_MAP[selectedCert.status]?.color}>
                  {STATUS_MAP[selectedCert.status]?.text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="证书名称" span={2}>{selectedCert.name}</Descriptions.Item>
              <Descriptions.Item label="类型">
                <Tag color={CERT_TYPE_MAP[selectedCert.type]?.color}>
                  {CERT_TYPE_MAP[selectedCert.type]?.label}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="关联产品">{selectedCert.productName || '-'}</Descriptions.Item>
              <Descriptions.Item label="到期日期">{selectedCert.expiryDate || '-'}</Descriptions.Item>
              <Descriptions.Item label="上传日期">{selectedCert.uploadDate || '-'}</Descriptions.Item>
              {selectedCert.approvedBy && (
                <Descriptions.Item label="审核人">{selectedCert.approvedBy}</Descriptions.Item>
              )}
              {selectedCert.approvedDate && (
                <Descriptions.Item label="审核日期">{selectedCert.approvedDate}</Descriptions.Item>
              )}
              {selectedCert.notes && (
                <Descriptions.Item label="备注" span={2}>{selectedCert.notes}</Descriptions.Item>
              )}
            </Descriptions>

            {selectedCert.fileUrl && (
              <>
                <Divider>附件</Divider>
                <Button icon={<DownloadOutlined />} size="small">
                  {selectedCert.fileName || '下载证书'}
                </Button>
              </>
            )}
          </>
        )}
      </Modal>
    </div>
  );
};

export default CertificateManage;
