import { useState, useEffect, useCallback } from 'react';
import { Card, Typography, Spin, Flex, Button, Tooltip, Tag } from 'antd';
import {
  MailOutlined,
  ReloadOutlined,
  TeamOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { api } from '@/lib/api';
import type { ListmonkStats, ListmonkStatus, ListmonkCampaignsData } from '@/types/api';

dayjs.extend(relativeTime);

const { Text } = Typography;

const CAMPAIGN_STATUS_COLORS: Record<string, string> = {
  running: 'green',
  finished: 'blue',
  paused: 'orange',
  draft: 'default',
  scheduled: 'purple',
  cancelled: 'red',
};

export default function NewsletterStatsCard() {
  const navigate = useNavigate();
  const [data, setData] = useState<ListmonkStats | null>(null);
  const [status, setStatus] = useState<ListmonkStatus | null>(null);
  const [campaigns, setCampaigns] = useState<ListmonkCampaignsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [hasError, setHasError] = useState(false);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const [statsRes, statusRes, campaignsRes] = await Promise.all([
        api.get<ListmonkStats>('/listmonk/stats'),
        api.get<ListmonkStatus>('/listmonk').catch(() => null),
        api.get<ListmonkCampaignsData>('/dashboard/listmonk-campaigns').catch(() => null),
      ]);
      setData(statsRes.data);
      if (statusRes) setStatus(statusRes.data);
      if (campaignsRes && !campaignsRes.data.error) setCampaigns(campaignsRes.data);
      setHasError(false);
    } catch {
      setHasError(true);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 5 * 60_000);
    return () => clearInterval(interval);
  }, [fetchData]);

  if (hasError && !data) return null;

  const lists = data?.lists || [];
  const totalSubscribers = lists.reduce((sum, l) => sum + l.subscriberCount, 0);
  const campaignList = campaigns?.campaigns || [];

  return (
    <Card
      title={<span style={{ fontSize: 14 }}><MailOutlined style={{ marginRight: 6, fontSize: 15 }} />Newsletter</span>}
      size="small"
      extra={
        <Flex align="center" gap={6}>
          <Button type="link" size="small" onClick={() => navigate('/app/listmonk')} style={{ fontSize: 12, padding: 0 }}>
            Manage
          </Button>
          <Button type="text" size="small" icon={<ReloadOutlined spin={loading} style={{ fontSize: 13 }} />} onClick={fetchData} />
        </Flex>
      }
      styles={{ body: { padding: '6px 14px 8px' } }}
    >
      {loading && !data ? (
        <div style={{ textAlign: 'center', padding: 12 }}><Spin size="small" /></div>
      ) : lists.length > 0 ? (
        <>
          <Flex align="center" gap={8} style={{ marginBottom: 8 }}>
            <TeamOutlined style={{ fontSize: 16, color: '#1890ff' }} />
            <Text strong style={{ fontSize: 18 }}>{totalSubscribers.toLocaleString()}</Text>
            <Text type="secondary" style={{ fontSize: 13 }}>total across {lists.length} lists</Text>
          </Flex>
          <div style={{ borderTop: '1px solid rgba(255,255,255,0.06)', paddingTop: 6 }}>
            {lists.slice(0, 6).map((list, i) => (
              <Flex key={i} justify="space-between" style={{ padding: '2px 0' }}>
                <Tooltip title={list.name}>
                  <Text style={{ fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '70%' }}>
                    {list.name}
                  </Text>
                </Tooltip>
                <Text type="secondary" style={{ fontSize: 12, flexShrink: 0 }}>{list.subscriberCount.toLocaleString()}</Text>
              </Flex>
            ))}
          </div>
          {/* Campaign Performance Section */}
          {campaignList.length > 0 && (
            <div style={{ borderTop: '1px solid rgba(255,255,255,0.06)', paddingTop: 6, marginTop: 6 }}>
              <Text type="secondary" style={{ fontSize: 11, display: 'block', marginBottom: 4 }}>Campaigns</Text>
              {campaignList.slice(0, 5).map((c, i) => (
                <Flex key={i} justify="space-between" align="center" style={{ padding: '2px 0' }}>
                  <Flex align="center" gap={4} style={{ overflow: 'hidden', flex: 1, minWidth: 0 }}>
                    <Tag color={CAMPAIGN_STATUS_COLORS[c.status] || 'default'} style={{ fontSize: 10, margin: 0, padding: '0 4px', flexShrink: 0 }}>
                      {c.status}
                    </Tag>
                    <Tooltip title={c.name}>
                      <Text style={{ fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {c.name}
                      </Text>
                    </Tooltip>
                  </Flex>
                  <Flex gap={8} style={{ flexShrink: 0 }}>
                    <Text type="secondary" style={{ fontSize: 11 }}>{c.sentCount.toLocaleString()} sent</Text>
                    <Text type="secondary" style={{ fontSize: 11 }}>{c.openRate}% open</Text>
                  </Flex>
                </Flex>
              ))}
            </div>
          )}
          {status?.lastSyncAt && (
            <Text type="secondary" style={{ fontSize: 11, display: 'block', marginTop: 4 }}>
              Last synced {dayjs(status.lastSyncAt).fromNow()}
            </Text>
          )}
        </>
      ) : (
        <Text type="secondary" style={{ fontSize: 13, display: 'block', padding: '8px 0' }}>No lists configured</Text>
      )}
    </Card>
  );
}
