import { useState, useEffect, useCallback } from 'react';
import { Drawer, Table, Tag, Select, Statistic, Row, Col, Card, message, Grid } from 'antd';
import type { TablePaginationConfig } from 'antd/es/table';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import type {
  Campaign,
  CampaignEmail,
  CampaignEmailStatus,
  CampaignEmailsListResponse,
  CampaignEmailStats,
  EmailMethod,
} from '@/types/api';

interface Props {
  campaign: Campaign | null;
  open: boolean;
  onClose: () => void;
}

const statusColors: Record<CampaignEmailStatus, string> = {
  QUEUED: 'processing',
  SENT: 'success',
  FAILED: 'error',
  CLICKED: 'blue',
  USER_INFO_CAPTURED: 'purple',
};

const statusOptions: { value: CampaignEmailStatus; label: string }[] = [
  { value: 'QUEUED', label: 'Queued' },
  { value: 'SENT', label: 'Sent' },
  { value: 'FAILED', label: 'Failed' },
  { value: 'CLICKED', label: 'Clicked (Mailto)' },
  { value: 'USER_INFO_CAPTURED', label: 'User Info Captured' },
];

export default function CampaignEmailsDrawer({ campaign, open, onClose }: Props) {
  const [emails, setEmails] = useState<CampaignEmail[]>([]);
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [pagination, setPagination] = useState({ page: 1, limit: 20, total: 0, totalPages: 0 });
  const [loading, setLoading] = useState(false);
  const [statusFilter, setStatusFilter] = useState<CampaignEmailStatus | undefined>();
  const [stats, setStats] = useState<CampaignEmailStats | null>(null);

  const fetchEmails = useCallback(async (page = 1) => {
    if (!campaign) return;
    setLoading(true);
    try {
      const { data } = await api.get<CampaignEmailsListResponse>(`/campaigns/${campaign.id}/emails`, {
        params: { page, limit: pagination.limit, status: statusFilter },
      });
      setEmails(data.emails);
      setPagination(data.pagination);
    } catch {
      message.error('Failed to load emails');
    } finally {
      setLoading(false);
    }
  }, [campaign, pagination.limit, statusFilter]);

  const fetchStats = useCallback(async () => {
    if (!campaign) return;
    try {
      const { data } = await api.get<CampaignEmailStats>(`/campaigns/${campaign.id}/email-stats`);
      setStats(data);
    } catch {
      // Silently fail — stats are informational
    }
  }, [campaign]);

  useEffect(() => {
    if (open && campaign) {
      fetchEmails(1);
      fetchStats();
    }
  }, [open, campaign, statusFilter]); // eslint-disable-line react-hooks/exhaustive-deps

  const handleTableChange = (pag: TablePaginationConfig) => {
    fetchEmails(pag.current ?? 1);
  };

  const columns = [
    {
      title: 'Recipient',
      dataIndex: 'recipientEmail',
      key: 'recipientEmail',
      ellipsis: true,
      render: (email: string, record: CampaignEmail) =>
        record.recipientName ? `${record.recipientName} <${email}>` : email,
    },
    {
      title: 'Sender',
      dataIndex: 'userName',
      key: 'userName',
      ellipsis: true,
      render: (name: string | null, record: CampaignEmail) => name || record.userEmail || '--',
    },
    {
      title: 'Method',
      dataIndex: 'emailMethod',
      key: 'emailMethod',
      render: (method: EmailMethod) => (
        <Tag color={method === 'SMTP' ? 'geekblue' : 'orange'}>{method}</Tag>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: CampaignEmailStatus) => (
        <Tag color={statusColors[status]}>{status}</Tag>
      ),
    },
    {
      title: 'Sent',
      dataIndex: 'sentAt',
      key: 'sentAt',
      render: (date: string) => dayjs(date).format('MM-DD HH:mm'),
    },
  ];

  return (
    <Drawer
      title={`Emails — ${campaign?.title || ''}`}
      open={open}
      onClose={onClose}
      width={isMobile ? '100%' : 720}
      destroyOnClose
    >
      {stats && (
        <Row gutter={[12, 12]} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Card size="small">
              <Statistic title="Sent" value={stats.sent} valueStyle={{ color: '#52c41a' }} />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic title="Queued" value={stats.queued} valueStyle={{ color: '#1890ff' }} />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic title="Failed" value={stats.failed} valueStyle={{ color: '#ff4d4f' }} />
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small">
              <Statistic title="Mailto" value={stats.clicked} valueStyle={{ color: '#fa8c16' }} />
            </Card>
          </Col>
        </Row>
      )}

      <Select
        placeholder="Filter by status"
        options={statusOptions}
        value={statusFilter}
        onChange={setStatusFilter}
        allowClear
        style={{ width: 200, marginBottom: 12 }}
      />

      <Table<CampaignEmail>
        columns={columns}
        dataSource={emails}
        rowKey="id"
        loading={loading}
        size="small"
        scroll={{ x: 'max-content' }}
        pagination={{
          current: pagination.page,
          pageSize: pagination.limit,
          total: pagination.total,
          showTotal: (total) => `${total} emails`,
          size: 'small',
        }}
        onChange={handleTableChange}
      />
    </Drawer>
  );
}
