import { useState, useEffect } from 'react';
import { Card, Table, Progress, Tag, Button, Spin } from 'antd';
import { ExportOutlined, FundOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import type { CutCampaignAnalytics } from '@/types/api';

const SUPPORT_LABELS: Record<string, { label: string; color: string }> = {
  LEVEL_1: { label: 'Strong', color: '#27ae60' },
  LEVEL_2: { label: 'Likely', color: '#f1c40f' },
  LEVEL_3: { label: 'Unsure', color: '#e67e22' },
  LEVEL_4: { label: 'Oppose', color: '#e74c3c' },
};

interface Props {
  onExportCut?: (cutId: string) => void;
}

export default function CutCampaignAnalyticsCard({ onExportCut }: Props) {
  const [data, setData] = useState<CutCampaignAnalytics[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.get<{ cuts: CutCampaignAnalytics[] }>('/map/canvass/analytics/cuts')
      .then(({ data: res }) => setData(res.cuts))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <Card title={<><FundOutlined style={{ marginRight: 6 }} />Campaign Readiness</>} size="small">
        <div style={{ textAlign: 'center', padding: 24 }}><Spin size="small" /></div>
      </Card>
    );
  }

  if (data.length === 0) return null;

  return (
    <Card
      title={<><FundOutlined style={{ marginRight: 6 }} />Campaign Readiness by Cut</>}
      size="small"
    >
      <Table
        dataSource={data}
        rowKey="cutId"
        size="small"
        pagination={false}
        scroll={{ x: 600 }}
        columns={[
          {
            title: 'Cut',
            dataIndex: 'cutName',
            key: 'cutName',
            width: 150,
            ellipsis: true,
          },
          {
            title: 'Completion',
            key: 'completion',
            width: 140,
            render: (_, r) => (
              <Progress
                percent={r.completionPct}
                size="small"
                strokeColor={r.completionPct >= 80 ? '#52c41a' : r.completionPct >= 40 ? '#faad14' : '#ff4d4f'}
              />
            ),
          },
          {
            title: 'Addresses',
            dataIndex: 'totalAddresses',
            key: 'total',
            width: 80,
            align: 'right' as const,
          },
          {
            title: 'With Email',
            dataIndex: 'addressesWithEmail',
            key: 'email',
            width: 90,
            align: 'right' as const,
            render: (v: number) => (
              <span style={{ color: v > 0 ? '#52c41a' : '#999' }}>{v}</span>
            ),
          },
          {
            title: 'Support',
            key: 'support',
            width: 180,
            render: (_, r) => (
              <div style={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}>
                {Object.entries(r.supportBreakdown).map(([level, count]) => {
                  const info = SUPPORT_LABELS[level];
                  if (!info || count === 0) return null;
                  return (
                    <Tag key={level} color={info.color} style={{ margin: 0, fontSize: 10, padding: '0 4px' }}>
                      {info.label}: {count}
                    </Tag>
                  );
                })}
              </div>
            ),
          },
          ...(onExportCut ? [{
            title: '',
            key: 'actions',
            width: 60,
            render: (_: unknown, r: CutCampaignAnalytics) => (
              <Button
                type="link"
                size="small"
                icon={<ExportOutlined />}
                onClick={() => onExportCut(r.cutId)}
                disabled={r.addressesWithEmail === 0}
              />
            ),
          }] : []),
        ]}
      />
    </Card>
  );
}
