import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Tag,
  Row,
  Col,
  Statistic,
  Alert,
  List,
  Badge,
  Tooltip,
  Switch,
  message,
  Divider,
  Timeline,
} from 'antd';
import {
  BellOutlined,
  ClockCircleOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SettingOutlined,
  MailOutlined,
  SyncOutlined,
  FileTextOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { certificateDataSource, Certificate } from '@/services/certificateDataSource';

interface ExpiryReminder {
  id: string;
  certNo: string;
  certName: string;
  certType: string;
  productName: string;
  expiryDate: string;
  daysRemaining: number;
  status: 'CRITICAL' | 'WARNING' | 'NOTICE' | 'SAFE';
  reminderSent: boolean;
  lastReminderDate?: string;
  nextReminderDate?: string;
  actions: string[];
}

const MOCK_REMINDERS: ExpiryReminder[] = [
  {
    id: '1',
    certNo: 'FCC-2025-045',
    certName: 'FCC Declaration',
    certType: 'FCC',
    productName: 'Control Module B',
    expiryDate: '2025-06-19',
    daysRemaining: 93,
    status: 'WARNING',
    reminderSent: true,
    lastReminderDate: '2025-03-15',
    nextReminderDate: '2025-04-15',
    actions: ['Initiate renewal process', 'Contact testing lab'],
  },
  {
    id: '2',
    certNo: 'RoHS-2024-112',
    certName: 'RoHS Compliance Certificate',
    certType: 'RoHS',
    productName: 'Power Supply Unit C',
    expiryDate: '2025-02-28',
    daysRemaining: -18,
    status: 'CRITICAL',
    reminderSent: true,
    lastReminderDate: '2025-03-01',
    actions: ['Immediate re-certification required', 'Suspend product listing'],
  },
  {
    id: '3',
    certNo: 'CE-2026-001',
    certName: 'CE Declaration of Conformity',
    certType: 'CE',
    productName: 'Industrial Sensor A',
    expiryDate: '2027-01-14',
    daysRemaining: 663,
    status: 'SAFE',
    reminderSent: false,
    actions: [],
  },
  {
    id: '4',
    certNo: 'UL-2026-008',
    certName: 'UL Safety Certification',
    certType: 'UL',
    productName: 'Communication Gateway D',
    expiryDate: '2027-01-31',
    daysRemaining: 680,
    status: 'SAFE',
    reminderSent: false,
    actions: [],
  },
  {
    id: '5',
    certNo: 'ISO-2025-022',
    certName: 'ISO 9001:2015',
    certType: 'ISO',
    productName: 'Company-wide',
    expiryDate: '2025-09-30',
    daysRemaining: 196,
    status: 'NOTICE',
    reminderSent: true,
    lastReminderDate: '2025-03-01',
    nextReminderDate: '2025-06-01',
    actions: ['Schedule surveillance audit', 'Update quality manual'],
  },
];

const STATUS_CONFIG: Record<string, { color: string; text: string; icon: React.ReactNode; bgColor: string }> = {
  CRITICAL: { color: 'error', text: 'Critical', icon: <CloseCircleOutlined />, bgColor: '#fff2f0' },
  WARNING: { color: 'warning', text: 'Warning', icon: <WarningOutlined />, bgColor: '#fffbe6' },
  NOTICE: { color: 'processing', text: 'Notice', icon: <ClockCircleOutlined />, bgColor: '#e6f7ff' },
  SAFE: { color: 'success', text: 'Safe', icon: <CheckCircleOutlined />, bgColor: '#f6ffed' },
};

export const CertificateExpiryReminder: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [reminders, setReminders] = useState<ExpiryReminder[]>(MOCK_REMINDERS);
  const [settingsModalVisible, setSettingsModalVisible] = useState(false);
  const [emailEnabled, setEmailEnabled] = useState(true);
  const [autoRenewal, setAutoRenewal] = useState(false);

  useEffect(() => {
    checkReminders();
  }, []);

  const checkReminders = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      message.success('Reminders checked');
    }, 1000);
  };

  const handleSendReminder = (reminder: ExpiryReminder) => {
    Modal.confirm({
      title: 'Send Reminder',
      content: `Send expiry reminder for ${reminder.certNo}?`,
      onOk: () => {
        setReminders(reminders.map(r => 
          r.id === reminder.id ? { ...r, reminderSent: true, lastReminderDate: new Date().toISOString().split('T')[0] } : r
        ));
        message.success('Reminder sent successfully');
      },
    });
  };

  const handleInitiateRenewal = (reminder: ExpiryReminder) => {
    Modal.confirm({
      title: 'Initiate Renewal',
      content: `Start renewal process for ${reminder.certNo}?`,
      onOk: () => {
        message.success('Renewal process initiated');
      },
    });
  };

  const getStatusTag = (status: string, days: number) => {
    const config = STATUS_CONFIG[status];
    if (days < 0) {
      return <Tag color="error" icon={<CloseCircleOutlined />}>EXPIRED</Tag>;
    }
    return <Tag color={config.color} icon={config.icon}>{config.text}</Tag>;
  };

  const criticalCount = reminders.filter(r => r.status === 'CRITICAL' || r.daysRemaining < 0).length;
  const warningCount = reminders.filter(r => r.status === 'WARNING').length;
  const noticeCount = reminders.filter(r => r.status === 'NOTICE').length;

  return (
    <div className="certificate-expiry-reminder-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic 
              title="Total Certificates" 
              value={reminders.length} 
              prefix={<FileTextOutlined />} 
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card style={{ background: STATUS_CONFIG.CRITICAL.bgColor }}>
            <Statistic 
              title="Critical / Expired" 
              value={criticalCount} 
              valueStyle={{ color: '#ff4d4f' }}
              prefix={<CloseCircleOutlined />} 
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card style={{ background: STATUS_CONFIG.WARNING.bgColor }}>
            <Statistic 
              title="Warning" 
              value={warningCount} 
              valueStyle={{ color: '#faad14' }}
              prefix={<WarningOutlined />} 
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card style={{ background: STATUS_CONFIG.NOTICE.bgColor }}>
            <Statistic 
              title="Notice" 
              value={noticeCount} 
              valueStyle={{ color: '#1890ff' }}
              prefix={<ClockCircleOutlined />} 
            />
          </Card>
        </Col>
      </Row>

      {criticalCount > 0 && (
        <Alert
          message="Critical Certificates Detected"
          description={`${criticalCount} certificate(s) have expired or are in critical status. Immediate action required to maintain compliance.`}
          type="error"
          showIcon
          icon={<CloseCircleOutlined />}
          style={{ marginBottom: 24 }}
          action={
            <Button size="small" danger onClick={() => message.info('Navigating to critical certificates...')}>
              View Details
            </Button>
          }
        />
      )}

      <Card 
        title="Certificate Expiry Reminders" 
        extra={
          <Space>
            <Button icon={<SyncOutlined />} onClick={checkReminders} loading={loading}>
              Refresh
            </Button>
            <Button icon={<SettingOutlined />} onClick={() => setSettingsModalVisible(true)}>
              Settings
            </Button>
          </Space>
        }
      >
        <List
          itemLayout="horizontal"
          dataSource={reminders.sort((a, b) => a.daysRemaining - b.daysRemaining)}
          renderItem={(item) => (
            <List.Item
              style={{ 
                background: item.daysRemaining < 0 ? '#fff2f0' : item.daysRemaining <= 90 ? '#fffbe6' : 'transparent',
                padding: 16,
                marginBottom: 8,
                borderRadius: 8,
              }}
              actions={[
                <Tooltip title="Send Reminder">
                  <Button 
                    type="link" 
                    icon={<MailOutlined />} 
                    onClick={() => handleSendReminder(item)}
                    disabled={item.reminderSent && item.daysRemaining > 30}
                  />
                </Tooltip>,
                <Tooltip title="Initiate Renewal">
                  <Button 
                    type="link" 
                    icon={<SyncOutlined />} 
                    onClick={() => handleInitiateRenewal(item)}
                    disabled={item.status === 'SAFE'}
                  />
                </Tooltip>,
              ]}
            >
              <List.Item.Meta
                avatar={
                  <Badge 
                    count={item.daysRemaining < 0 ? '!' : item.daysRemaining <= 30 ? item.daysRemaining : 0} 
                    offset={[-5, 5]}
                  >
                    <FileTextOutlined style={{ fontSize: 32, color: item.daysRemaining < 0 ? '#ff4d4f' : item.daysRemaining <= 90 ? '#faad14' : '#52c41a' }} />
                  </Badge>
                }
                title={
                  <Space>
                    <span>{item.certNo}</span>
                    {getStatusTag(item.status, item.daysRemaining)}
                    {item.reminderSent && <Tag icon={<BellOutlined />} color="blue">Reminder Sent</Tag>}
                  </Space>
                }
                description={
                  <>
                    <div>{item.certName} - {item.productName}</div>
                    <Space style={{ marginTop: 8 }}>
                      <span>Expiry: {item.expiryDate}</span>
                      <Divider type="vertical" />
                      <span style={{ 
                        color: item.daysRemaining < 0 ? '#ff4d4f' : item.daysRemaining <= 90 ? '#faad14' : '#52c41a',
                        fontWeight: 'bold'
                      }}>
                        {item.daysRemaining < 0 
                          ? `Expired ${Math.abs(item.daysRemaining)} days ago` 
                          : `${item.daysRemaining} days remaining`
                        }
                      </span>
                    </Space>
                  </>
                }
              />
              {item.actions.length > 0 && (
                <div style={{ marginLeft: 48 }}>
                  <Timeline
                    items={item.actions.map((action, index) => ({
                      color: index === 0 ? 'red' : 'gray',
                      children: action,
                    }))}
                  />
                </div>
              )}
            </List.Item>
          )}
        />
      </Card>

      <Modal
        title="Reminder Settings"
        open={settingsModalVisible}
        onCancel={() => setSettingsModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setSettingsModalVisible(false)}>Close</Button>,
          <Button key="save" type="primary" onClick={() => { message.success('Settings saved'); setSettingsModalVisible(false); }}>
            Save Settings
          </Button>,
        ]}
      >
        <div style={{ padding: '16px 0' }}>
          <div style={{ marginBottom: 24 }}>
            <div style={{ marginBottom: 8, fontWeight: 500 }}>Email Notifications</div>
            <Switch 
              checked={emailEnabled} 
              onChange={setEmailEnabled}
              checkedChildren="Enabled"
              unCheckedChildren="Disabled"
            />
            <div style={{ color: '#666', marginTop: 8 }}>
              Receive email notifications for certificate expiry reminders
            </div>
          </div>

          <div style={{ marginBottom: 24 }}>
            <div style={{ marginBottom: 8, fontWeight: 500 }}>Auto-initiate Renewal</div>
            <Switch 
              checked={autoRenewal} 
              onChange={setAutoRenewal}
              checkedChildren="Enabled"
              unCheckedChildren="Disabled"
            />
            <div style={{ color: '#666', marginTop: 8 }}>
              Automatically initiate renewal process when certificate enters warning status
            </div>
          </div>

          <Divider>Reminder Schedule</Divider>

          <List
            size="small"
            dataSource={[
              { status: 'Critical', timing: '90 days before expiry', frequency: 'Weekly' },
              { status: 'Warning', timing: '60 days before expiry', frequency: 'Bi-weekly' },
              { status: 'Notice', timing: '30 days before expiry', frequency: 'Weekly' },
              { status: 'Final', timing: '7 days before expiry', frequency: 'Daily' },
            ]}
            renderItem={(item) => (
              <List.Item>
                <List.Item.Meta
                  title={item.status}
                  description={`${item.timing} - ${item.frequency}`}
                />
              </List.Item>
            )}
          />
        </div>
      </Modal>
    </div>
  );
};

export default CertificateExpiryReminder;
