import { useState, useEffect, useCallback } from 'react';
import { Card, Typography, Spin, Flex, Button, Statistic, Tag, Tooltip } from 'antd';
import {
  FundOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';
import type { CampaignOverviewStats } from '@/types/api';

const { Text } = Typography;

export default function CampaignEffectivenessCard() {
  const navigate = useNavigate();
  const [data, setData] = useState<CampaignOverviewStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [hasError, setHasError] = useState(false);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get<CampaignOverviewStats>('/influence/effectiveness/overview');
      setData(res.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 s = data?.summary;
  const topCampaigns = data?.campaigns?.slice(0, 3) || [];

  return (
    <Card
      title={<span style={{ fontSize: 14 }}><FundOutlined style={{ marginRight: 6, fontSize: 15 }} />Campaign Effectiveness</span>}
      size="small"
      extra={
        <Flex align="center" gap={6}>
          <Button type="link" size="small" onClick={() => navigate('/app/influence/effectiveness')} style={{ fontSize: 12, padding: 0 }}>
            Details
          </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>
      ) : s ? (
        <>
          <Flex gap={16} wrap="wrap" style={{ marginBottom: 8 }}>
            <Statistic
              title={<Text style={{ fontSize: 11 }}>Emails Sent</Text>}
              value={s.totalEmails}
              valueStyle={{ fontSize: 18 }}
            />
            <Statistic
              title={<Text style={{ fontSize: 11 }}>Responses</Text>}
              value={s.totalResponses}
              valueStyle={{ fontSize: 18 }}
            />
            <Statistic
              title={<Text style={{ fontSize: 11 }}>Response Rate</Text>}
              value={Math.round(s.avgResponseRate * 100)}
              suffix="%"
              valueStyle={{ fontSize: 18, color: s.avgResponseRate > 0.1 ? '#52c41a' : '#faad14' }}
            />
          </Flex>
          {topCampaigns.length > 0 && (
            <div style={{ borderTop: '1px solid rgba(255,255,255,0.06)', paddingTop: 6 }}>
              <Text type="secondary" style={{ fontSize: 11, display: 'block', marginBottom: 4 }}>Top Campaigns</Text>
              {topCampaigns.map(c => (
                <Flex key={c.campaignId} justify="space-between" align="center" style={{ padding: '2px 0' }}>
                  <Tooltip title={c.title}>
                    <Text style={{ fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '60%' }}>
                      {c.title}
                    </Text>
                  </Tooltip>
                  <Flex gap={6} style={{ flexShrink: 0 }}>
                    <Text type="secondary" style={{ fontSize: 11 }}>{c.emailTotal} emails</Text>
                    <Tag color={c.responseRate > 0.1 ? 'green' : 'default'} style={{ fontSize: 10, margin: 0, padding: '0 4px', lineHeight: '18px' }}>
                      {Math.round(c.responseRate * 100)}%
                    </Tag>
                  </Flex>
                </Flex>
              ))}
            </div>
          )}
        </>
      ) : (
        <Text type="secondary" style={{ fontSize: 13, display: 'block', padding: '8px 0' }}>No campaign data</Text>
      )}
    </Card>
  );
}
