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';

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

interface Certificate {
  id: string;
  certNo: string;
  certName: string;
  certType: 'CE' | 'FCC' | 'RoHS' | 'UL' | 'ISO' | 'FDA' | 'CCC' | 'OTHER';
  productId: string;
  productName: string;
  issuer: string;
  issueDate: string;
  expiryDate: string;
  status: 'VALID' | 'EXPIRED' | 'PENDING_RENEWAL' | 'REVOKED';
  attachments: string[];
  scope: string;
  remark?: string;
  createdAt: string;
  updatedAt: string;
}

const CERT_TYPES = [
  { value: 'CE', label: 'CE Certification', color: 'blue' },
  { value: 'FCC', label: 'FCC Certification', color: 'green' },
  { value: 'RoHS', label: 'RoHS Compliance', color: 'purple' },
  { value: 'UL', label: 'UL Certification', color: 'orange' },
  { value: 'ISO', label: 'ISO Certification', color: 'cyan' },
  { value: 'FDA', label: 'FDA Approval', color: 'red' },
  { value: 'CCC', label: 'CCC Certification', color: 'gold' },
  { value: 'OTHER', label: 'Other', color: 'default' },
];

const STATUS_CONFIG: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  VALID: { color: 'success', text: 'Valid', icon: <CheckCircleOutlined /> },
  EXPIRED: { color: 'error', text: 'Expired', icon: <CloseCircleOutlined /> },
  PENDING_RENEWAL: { color: 'warning', text: 'Pending Renewal', icon: <ClockCircleOutlined /> },
  REVOKED: { color: 'red', text: 'Revoked', icon: <CloseCircleOutlined /> },
};

const MOCK_PRODUCTS = [
  { id: 'P001', name: 'Industrial Sensor A' },
  { id: 'P002', name: 'Control Module B' },
  { id: 'P003', name: 'Power Supply Unit C' },
  { id: 'P004', name: 'Communication Gateway 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();
  }, []);

  const fetchCertificates = async () => {
    setLoading(true);
    try {
      const mockCerts: Certificate[] = [
        {
          id: '1',
          certNo: 'CE-2026-001',
          certName: 'CE Declaration of Conformity',
          certType: 'CE',
          productId: 'P001',
          productName: 'Industrial Sensor A',
          issuer: 'TÜV SÜD',
          issueDate: '2025-01-15',
          expiryDate: '2027-01-14',
          status: 'VALID',
          attachments: ['ce_cert_2026_001.pdf', 'test_report.pdf'],
          scope: 'Low Voltage Directive (LVD), EMC Directive',
          createdAt: '2025-01-15 10:00:00',
          updatedAt: '2025-01-15 10:00:00',
        },
        {
          id: '2',
          certNo: 'FCC-2025-045',
          certName: 'FCC Declaration',
          certType: 'FCC',
          productId: 'P002',
          productName: 'Control Module B',
          issuer: 'FCC',
          issueDate: '2024-06-20',
          expiryDate: '2025-06-19',
          status: 'PENDING_RENEWAL',
          attachments: ['fcc_cert.pdf'],
          scope: 'Part 15B Class B Digital Device',
          remark: 'Renewal application submitted',
          createdAt: '2024-06-20 14:30:00',
          updatedAt: '2025-03-10 09:00:00',
        },
        {
          id: '3',
          certNo: 'RoHS-2024-112',
          certName: 'RoHS Compliance Certificate',
          certType: 'RoHS',
          productId: 'P003',
          productName: 'Power Supply Unit C',
          issuer: 'SGS',
          issueDate: '2024-03-01',
          expiryDate: '2025-02-28',
          status: 'EXPIRED',
          attachments: ['rohs_cert.pdf'],
          scope: 'RoHS 2.0 (2011/65/EU)',
          remark: 'Needs re-certification',
          createdAt: '2024-03-01 09:00:00',
          updatedAt: '2025-03-01 00:00:00',
        },
        {
          id: '4',
          certNo: 'UL-2026-008',
          certName: 'UL Safety Certification',
          certType: 'UL',
          productId: 'P004',
          productName: 'Communication Gateway D',
          issuer: 'Underwriters Laboratories',
          issueDate: '2026-02-01',
          expiryDate: '2027-01-31',
          status: 'VALID',
          attachments: ['ul_cert.pdf', 'safety_test.pdf'],
          scope: 'UL 60950-1, Information Technology Equipment',
          createdAt: '2026-02-01 11:00:00',
          updatedAt: '2026-02-01 11:00:00',
        },
      ];
      setCertificates(mockCerts);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateCert = async (values: any) => {
    setLoading(true);
    try {
      const product = MOCK_PRODUCTS.find(p => p.id === values.productId);
      const newCert: Certificate = {
        id: `${Date.now()}`,
        certNo: `${values.certType}-${new Date().getFullYear()}-${String(certificates.length + 1).padStart(3, '0')}`,
        certName: values.certName,
        certType: values.certType,
        productId: values.productId,
        productName: product?.name || '',
        issuer: values.issuer,
        issueDate: values.issueDate.format('YYYY-MM-DD'),
        expiryDate: values.expiryDate.format('YYYY-MM-DD'),
        status: 'VALID',
        attachments: [],
        scope: values.scope,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };

      setCertificates([newCert, ...certificates]);
      message.success('Certificate created successfully');
      setCreateModalVisible(false);
      form.resetFields();
    } finally {
      setLoading(false);
    }
  };

  const handleViewDetail = (cert: Certificate) => {
    setSelectedCert(cert);
    setDetailModalVisible(true);
  };

  const handleRenew = (cert: Certificate) => {
    Modal.confirm({
      title: 'Renew Certificate',
      content: `Are you sure you want to initiate renewal for ${cert.certNo}?`,
      onOk: () => {
        setCertificates(certificates.map(c => 
          c.id === cert.id ? { ...c, status: 'PENDING_RENEWAL' as const, updatedAt: new Date().toISOString() } : c
        ));
        message.success('Renewal initiated');
      },
    });
  };

  const handleDelete = (certId: string) => {
    Modal.confirm({
      title: 'Delete Certificate',
      content: 'Are you sure you want to delete this certificate?',
      okType: 'danger',
      onOk: () => {
        setCertificates(certificates.filter(c => c.id !== certId));
        message.success('Certificate deleted');
      },
    });
  };

  const getFilteredCerts = () => {
    if (activeTab === 'all') return certificates;
    if (activeTab === 'expiring') {
      return certificates.filter(c => {
        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: 'Cert No',
      dataIndex: 'certNo',
      key: 'certNo',
      width: 130,
      render: (no: string, record: Certificate) => (
        <a onClick={() => handleViewDetail(record)}>{no}</a>
      ),
    },
    {
      title: 'Certificate Name',
      dataIndex: 'certName',
      key: 'certName',
      width: 200,
      ellipsis: true,
    },
    {
      title: 'Type',
      dataIndex: 'certType',
      key: 'certType',
      width: 100,
      render: (type: string) => {
        const config = CERT_TYPES.find(t => t.value === type);
        return <Tag color={config?.color}>{type}</Tag>;
      },
    },
    {
      title: 'Product',
      dataIndex: 'productName',
      key: 'productName',
      width: 160,
    },
    {
      title: 'Issuer',
      dataIndex: 'issuer',
      key: 'issuer',
      width: 120,
    },
    {
      title: 'Issue Date',
      dataIndex: 'issueDate',
      key: 'issueDate',
      width: 100,
    },
    {
      title: 'Expiry Date',
      dataIndex: 'expiryDate',
      key: 'expiryDate',
      width: 100,
      render: (date: string, record: Certificate) => {
        const daysUntilExpiry = dayjs(date).diff(dayjs(), 'day');
        const isExpiringSoon = daysUntilExpiry > 0 && daysUntilExpiry <= 90;
        return (
          <Tooltip title={isExpiringSoon ? `Expires in ${daysUntilExpiry} days` : ''}>
            <span style={{ color: isExpiringSoon || daysUntilExpiry <= 0 ? '#ff4d4f' : undefined }}>
              {date}
            </span>
          </Tooltip>
        );
      },
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: string) => {
        const config = STATUS_CONFIG[status];
        return <Tag color={config.color} icon={config.icon}>{config.text}</Tag>;
      },
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 150,
      render: (_, record: Certificate) => (
        <Space>
          <Tooltip title="View Details">
            <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)} />
          </Tooltip>
          {record.status === 'VALID' && (
            <Tooltip title="Renew">
              <Button type="link" icon={<ClockCircleOutlined />} onClick={() => handleRenew(record)} />
            </Tooltip>
          )}
          <Tooltip title="Delete">
            <Button type="link" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record.id)} />
          </Tooltip>
        </Space>
      ),
    },
  ];

  const stats = {
    total: certificates.length,
    valid: certificates.filter(c => c.status === 'VALID').length,
    expiring: certificates.filter(c => {
      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="Total Certificates" value={stats.total} prefix={<FileTextOutlined />} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic title="Valid" value={stats.valid} valueStyle={{ color: '#52c41a' }} prefix={<CheckCircleOutlined />} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic title="Expiring Soon" value={stats.expiring} valueStyle={{ color: '#faad14' }} prefix={<WarningOutlined />} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic title="Expired" value={stats.expired} valueStyle={{ color: '#ff4d4f' }} prefix={<CloseCircleOutlined />} />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Alert
              message="Certificate Expiry Reminder"
              description={`${stats.expiring} certificates are expiring within 90 days. Please initiate renewal process.`}
              type="warning"
              showIcon
              icon={<BellOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Card title="Certificate Management" extra={
        <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateModalVisible(true)}>
          Add Certificate
        </Button>
      }>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="All" key="all" />
          <TabPane tab={<Badge count={stats.expiring} offset={[10, 0]} size="small">Expiring Soon</Badge>} key="expiring" />
          <TabPane tab="Valid" key="valid" />
          <TabPane tab="Expired" key="expired" />
          <TabPane tab="Pending Renewal" key="pending_renewal" />
        </Tabs>

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

      <Modal
        title="Add New Certificate"
        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="certType" label="Certificate Type" rules={[{ required: true }]}>
                <Select placeholder="Select Type">
                  {CERT_TYPES.map(t => (
                    <Option key={t.value} value={t.value}>{t.label}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="productId" label="Product" rules={[{ required: true }]}>
                <Select placeholder="Select Product">
                  {MOCK_PRODUCTS.map(p => (
                    <Option key={p.id} value={p.id}>{p.name}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="certName" label="Certificate Name" rules={[{ required: true }]}>
            <Input placeholder="Enter certificate name" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="issuer" label="Issuing Authority" rules={[{ required: true }]}>
                <Input placeholder="Enter issuer name" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="issueDate" label="Issue Date" rules={[{ required: true }]}>
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="expiryDate" label="Expiry Date" rules={[{ required: true }]}>
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="scope" label="Scope">
            <Input.TextArea rows={3} placeholder="Enter certification scope" />
          </Form.Item>

          <Form.Item name="attachments" label="Attachments">
            <Upload>
              <Button icon={<UploadOutlined />}>Upload Files</Button>
            </Upload>
          </Form.Item>

          <div style={{ textAlign: 'right' }}>
            <Button onClick={() => setCreateModalVisible(false)} style={{ marginRight: 8 }}>Cancel</Button>
            <Button type="primary" htmlType="submit" loading={loading}>Create Certificate</Button>
          </div>
        </Form>
      </Modal>

      <Modal
        title="Certificate Details"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>Close</Button>,
          selectedCert?.status === 'VALID' && (
            <Button key="renew" type="primary" icon={<ClockCircleOutlined />} onClick={() => { handleRenew(selectedCert); setDetailModalVisible(false); }}>
              Initiate Renewal
            </Button>
          ),
        ]}
        width={700}
      >
        {selectedCert && (
          <>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="Certificate No">{selectedCert.certNo}</Descriptions.Item>
              <Descriptions.Item label="Status">
                <Tag color={STATUS_CONFIG[selectedCert.status].color}>
                  {STATUS_CONFIG[selectedCert.status].text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Certificate Name" span={2}>{selectedCert.certName}</Descriptions.Item>
              <Descriptions.Item label="Type">
                <Tag color={CERT_TYPES.find(t => t.value === selectedCert.certType)?.color}>
                  {CERT_TYPES.find(t => t.value === selectedCert.certType)?.label}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Product">{selectedCert.productName}</Descriptions.Item>
              <Descriptions.Item label="Issuer">{selectedCert.issuer}</Descriptions.Item>
              <Descriptions.Item label="Issue Date">{selectedCert.issueDate}</Descriptions.Item>
              <Descriptions.Item label="Expiry Date">{selectedCert.expiryDate}</Descriptions.Item>
              <Descriptions.Item label="Scope" span={2}>{selectedCert.scope}</Descriptions.Item>
              {selectedCert.remark && (
                <Descriptions.Item label="Remark" span={2}>{selectedCert.remark}</Descriptions.Item>
              )}
            </Descriptions>

            {selectedCert.attachments.length > 0 && (
              <>
                <Divider>Attachments</Divider>
                <Space>
                  {selectedCert.attachments.map((file, index) => (
                    <Button key={index} icon={<DownloadOutlined />} size="small">
                      {file}
                    </Button>
                  ))}
                </Space>
              </>
            )}
          </>
        )}
      </Modal>
    </div>
  );
};

export default CertificateManage;
