import React, { useState } from 'react';
import { Card, Table, Button, Select, DatePicker, Space, Modal, Typography, Badge, message, Tabs, Row, Col, Statistic, Input, Alert } from 'antd';
import { PlusOutlined, EyeOutlined, EditOutlined, DeleteOutlined, ReloadOutlined, WarningOutlined, CheckCircleOutlined, ExclamationCircleOutlined, SafetyCertificateOutlined, FileTextOutlined } from '@ant-design/icons';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { Title, Text } = Typography;
const { TabPane } = Tabs;

const mockCertificates = [
  {
    id: '1',
    certificateNo: 'CERT-2026-001',
    name: 'CE Certification',
    type: 'Product Safety',
    status: 'valid',
    expiryDate: '2026-12-31',
    issuingAuthority: 'European Commission',
    products: ['Wireless Headphones', 'Bluetooth Speaker'],
    document: 'ce-cert-001.pdf',
    createdAt: '2026-01-15',
    updatedAt: '2026-03-18',
  },
  {
    id: '2',
    certificateNo: 'CERT-2026-002',
    name: 'FCC Certification',
    type: 'Electromagnetic Compatibility',
    status: 'valid',
    expiryDate: '2027-06-30',
    issuingAuthority: 'Federal Communications Commission',
    products: ['Smart Watch', 'Fitness Tracker'],
    document: 'fcc-cert-002.pdf',
    createdAt: '2026-02-20',
    updatedAt: '2026-03-18',
  },
  {
    id: '3',
    certificateNo: 'CERT-2026-003',
    name: 'RoHS Certification',
    type: 'Environmental',
    status: 'expiring',
    expiryDate: '2026-04-30',
    issuingAuthority: 'European Union',
    products: ['Home Decor Set'],
    document: 'rohs-cert-003.pdf',
    createdAt: '2026-01-10',
    updatedAt: '2026-03-18',
  },
  {
    id: '4',
    certificateNo: 'CERT-2026-004',
    name: 'ISO 9001 Certification',
    type: 'Quality Management',
    status: 'expired',
    expiryDate: '2026-02-28',
    issuingAuthority: 'International Organization for Standardization',
    products: ['All Products'],
    document: 'iso-9001-004.pdf',
    createdAt: '2025-12-01',
    updatedAt: '2026-03-01',
  },
];

const mockComplianceChecks = [
  {
    id: '1',
    checkNo: 'COMP-2026-001',
    productId: 'P001',
    productName: 'Wireless Headphones',
    platform: 'Amazon',
    checkType: 'Product Listing',
    status: 'passed',
    issues: [],
    checkedAt: '2026-03-18',
    checkedBy: 'System',
  },
  {
    id: '2',
    checkNo: 'COMP-2026-002',
    productId: 'P002',
    productName: 'Bluetooth Speaker',
    platform: 'eBay',
    checkType: 'Product Listing',
    status: 'warning',
    issues: ['Missing product description', 'Incomplete specifications'],
    checkedAt: '2026-03-18',
    checkedBy: 'System',
  },
  {
    id: '3',
    checkNo: 'COMP-2026-003',
    productId: 'P003',
    productName: 'Smart Watch',
    platform: 'Shopee',
    checkType: 'Product Listing',
    status: 'failed',
    issues: ['Invalid certificate', 'Missing safety warnings'],
    checkedAt: '2026-03-17',
    checkedBy: 'System',
  },
];

const CompliancePage: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [selectedCertificate, setSelectedCertificate] = useState<any>(null);
  const [activeTab, setActiveTab] = useState('certificates');
  const [searchKeyword, setSearchKeyword] = useState('');

  const handleViewDetail = (record: any) => {
    setSelectedCertificate(record);
    setIsDetailModalVisible(true);
  };

  const handleAddCertificate = () => {
    message.success('Add certificate form opened');
  };

  const handleEditCertificate = (record: any) => {
    message.success(`Edit certificate ${record.certificateNo}`);
  };

  const handleDeleteCertificate = (record: any) => {
    message.success(`Delete certificate ${record.certificateNo}`);
  };

  const handleRenewCertificate = (record: any) => {
    message.success(`Renew certificate ${record.certificateNo}`);
  };

  const handleRunComplianceCheck = () => {
    message.success('Compliance check initiated');
  };

  const handleBatchDelete = () => {
    message.success('Batch delete initiated');
  };

  const handleBatchRenew = () => {
    message.success('Batch renew initiated');
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'valid': return 'success';
      case 'expiring': return 'warning';
      case 'expired': return 'error';
      case 'passed': return 'success';
      case 'warning': return 'warning';
      case 'failed': return 'error';
      default: return 'default';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'valid': return <CheckCircleOutlined />;
      case 'expiring': return <ExclamationCircleOutlined />;
      case 'expired': return <WarningOutlined />;
      case 'passed': return <CheckCircleOutlined />;
      case 'warning': return <ExclamationCircleOutlined />;
      case 'failed': return <WarningOutlined />;
      default: return null;
    }
  };

  const certificateColumns = [
    {
      title: 'Certificate No',
      dataIndex: 'certificateNo',
      key: 'certificateNo',
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'Type',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Badge status={getStatusColor(status)} text={status} />
      ),
    },
    {
      title: 'Expiry Date',
      dataIndex: 'expiryDate',
      key: 'expiryDate',
      render: (date: string) => {
        const expiryDate = new Date(date);
        const today = new Date();
        const daysUntilExpiry = Math.ceil((expiryDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
        
        if (daysUntilExpiry < 0) {
          return <span style={{ color: '#f5222d' }}>{date} (Expired)</span>;
        } else if (daysUntilExpiry <= 30) {
          return <span style={{ color: '#faad14' }}>{date} (Expiring Soon)</span>;
        } else {
          return <span style={{ color: '#52c41a' }}>{date}</span>;
        }
      },
    },
    {
      title: 'Issuing Authority',
      dataIndex: 'issuingAuthority',
      key: 'issuingAuthority',
    },
    {
      title: 'Products',
      dataIndex: 'products',
      key: 'products',
      render: (products: string[]) => products.join(', '),
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button icon={<EyeOutlined />} onClick={() => handleViewDetail(record)}>View</Button>
          <Button icon={<EditOutlined />} onClick={() => handleEditCertificate(record)}>Edit</Button>
          <Button icon={<SafetyCertificateOutlined />} onClick={() => handleRenewCertificate(record)}>Renew</Button>
          <Button icon={<DeleteOutlined />} danger onClick={() => handleDeleteCertificate(record)}>Delete</Button>
        </Space>
      ),
    },
  ];

  const checkColumns = [
    {
      title: 'Check No',
      dataIndex: 'checkNo',
      key: 'checkNo',
    },
    {
      title: 'Product',
      dataIndex: 'productName',
      key: 'productName',
    },
    {
      title: 'Platform',
      dataIndex: 'platform',
      key: 'platform',
    },
    {
      title: 'Check Type',
      dataIndex: 'checkType',
      key: 'checkType',
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Badge status={getStatusColor(status)} text={status} />
      ),
    },
    {
      title: 'Issues',
      dataIndex: 'issues',
      key: 'issues',
      render: (issues: string[]) => (
        <div>
          {issues.length === 0 ? (
            <Text type="success">No issues</Text>
          ) : (
            issues.map((issue, index) => (
              <div key={index} style={{ color: '#f5222d' }}>
                {issue}
              </div>
            ))
          )}
        </div>
      ),
    },
    {
      title: 'Checked At',
      dataIndex: 'checkedAt',
      key: 'checkedAt',
    },
    {
      title: 'Checked By',
      dataIndex: 'checkedBy',
      key: 'checkedBy',
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: React.Key[]) => {
      setSelectedRowKeys(keys);
    },
  };

  const filteredCertificates = mockCertificates.filter(certificate =>
    certificate.name.toLowerCase().includes(searchKeyword.toLowerCase()) ||
    certificate.certificateNo.toLowerCase().includes(searchKeyword.toLowerCase())
  );

  return (
    <div className="compliance-page">
      <div className="page-header" style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Title level={4}>Compliance Management</Title>
        <Space>
          <Button icon={<PlusOutlined />} type="primary" onClick={handleAddCertificate}>Add Certificate</Button>
          <Button icon={<ReloadOutlined />}>Refresh</Button>
          <Button icon={<SafetyCertificateOutlined />} onClick={handleRunComplianceCheck}>Run Compliance Check</Button>
          <Button onClick={handleBatchRenew} disabled={selectedRowKeys.length === 0}>Batch Renew</Button>
          <Button onClick={handleBatchDelete} disabled={selectedRowKeys.length === 0} danger>Batch Delete</Button>
        </Space>
      </div>

      <Card style={{ marginBottom: 24 }}>
        <Row gutter={[16, 16]}>
          <Col span={6}>
            <Statistic
              title="Total Certificates"
              value={4}
              valueStyle={{ color: '#3f8600' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Valid Certificates"
              value={2}
              valueStyle={{ color: '#52c41a' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Expiring Soon"
              value={1}
              valueStyle={{ color: '#faad14' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Expired Certificates"
              value={1}
              valueStyle={{ color: '#f5222d' }}
            />
          </Col>
        </Row>
      </Card>

      <Alert
        message="Certificate Expiry Warning"
        description="You have 1 certificate expiring within 30 days and 1 expired certificate. Please renew them as soon as possible."
        type="warning"
        showIcon
        style={{ marginBottom: 24 }}
      />

      <Card style={{ marginBottom: 24 }}>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="Certificates" key="certificates">
            <div style={{ display: 'flex', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
              <Input
                placeholder="Search by certificate name or number"
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                style={{ width: 300 }}
                allowClear
              />
              <Select placeholder="Select Type" style={{ width: 150 }}>
                <Option value="all">All Types</Option>
                <Option value="Product Safety">Product Safety</Option>
                <Option value="Electromagnetic Compatibility">Electromagnetic Compatibility</Option>
                <Option value="Environmental">Environmental</Option>
                <Option value="Quality Management">Quality Management</Option>
              </Select>
              <Select placeholder="Select Status" style={{ width: 150 }}>
                <Option value="all">All Status</Option>
                <Option value="valid">Valid</Option>
                <Option value="expiring">Expiring Soon</Option>
                <Option value="expired">Expired</Option>
              </Select>
              <RangePicker style={{ width: 300 }} />
            </div>

            <Table
              rowSelection={rowSelection}
              columns={certificateColumns}
              dataSource={filteredCertificates}
              rowKey="id"
              pagination={{
                pageSize: 10,
              }}
            />
          </TabPane>
          <TabPane tab="Compliance Checks" key="checks">
            <div style={{ display: 'flex', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
              <Select placeholder="Select Platform" style={{ width: 150 }}>
                <Option value="all">All Platforms</Option>
                <Option value="amazon">Amazon</Option>
                <Option value="ebay">eBay</Option>
                <Option value="shopee">Shopee</Option>
              </Select>
              <Select placeholder="Select Status" style={{ width: 150 }}>
                <Option value="all">All Status</Option>
                <Option value="passed">Passed</Option>
                <Option value="warning">Warning</Option>
                <Option value="failed">Failed</Option>
              </Select>
              <RangePicker style={{ width: 300 }} />
            </div>

            <Table
              columns={checkColumns}
              dataSource={mockComplianceChecks}
              rowKey="id"
              pagination={{
                pageSize: 10,
              }}
            />
          </TabPane>
        </Tabs>
      </Card>

      <Modal
        title={`Certificate Detail - ${selectedCertificate?.name}`}
        open={isDetailModalVisible}
        onCancel={() => setIsDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setIsDetailModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={800}
      >
        {selectedCertificate && (
          <div>
            <div style={{ marginBottom: 24 }}>
              <h3>Basic Information</h3>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 16 }}>
                <div>
                  <Text strong>Certificate No:</Text> {selectedCertificate.certificateNo}
                </div>
                <div>
                  <Text strong>Name:</Text> {selectedCertificate.name}
                </div>
                <div>
                  <Text strong>Type:</Text> {selectedCertificate.type}
                </div>
                <div>
                  <Text strong>Status:</Text> <Badge status={getStatusColor(selectedCertificate.status)} text={selectedCertificate.status} />
                </div>
                <div>
                  <Text strong>Expiry Date:</Text> {selectedCertificate.expiryDate}
                </div>
                <div>
                  <Text strong>Issuing Authority:</Text> {selectedCertificate.issuingAuthority}
                </div>
                <div>
                  <Text strong>Created At:</Text> {selectedCertificate.createdAt}
                </div>
                <div>
                  <Text strong>Updated At:</Text> {selectedCertificate.updatedAt}
                </div>
              </div>
            </div>
            <div>
              <h3>Products</h3>
              <div style={{ marginTop: 16 }}>
                {selectedCertificate.products.map((product: string, index: number) => (
                  <div key={index} style={{ marginBottom: 8 }}>
                    <Badge status="success" text={product} />
                  </div>
                ))}
              </div>
            </div>
            <div style={{ marginTop: 24 }}>
              <h3>Document</h3>
              <div style={{ marginTop: 16 }}>
                <Button icon={<FileTextOutlined />} onClick={() => message.success('Download document')}>
                  {selectedCertificate.document}
                </Button>
              </div>
            </div>
            <div style={{ marginTop: 24 }}>
              <h3>Quick Actions</h3>
              <Space size="middle" style={{ marginTop: 16 }}>
                <Button icon={<SafetyCertificateOutlined />} onClick={() => handleRenewCertificate(selectedCertificate)}>Renew</Button>
                <Button icon={<EditOutlined />} onClick={() => handleEditCertificate(selectedCertificate)}>Edit</Button>
              </Space>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default CompliancePage;