import { useState, useEffect, useCallback } from 'react';
import { Card, Typography, Spin, Flex, Button, Statistic, Tag } from 'antd';
import {
  DollarOutlined,
  ReloadOutlined,
} 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 { PaymentDashboardStats } from '@/types/api';

dayjs.extend(relativeTime);

const { Text } = Typography;

function formatCents(cents: number): string {
  return `$${(cents / 100).toFixed(2)}`;
}

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

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get<PaymentDashboardStats>('/payments/admin/dashboard');
      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 recent = data?.donations?.recentDonations?.slice(0, 4) || [];

  return (
    <Card
      title={<span style={{ fontSize: 14 }}><DollarOutlined style={{ marginRight: 6, fontSize: 15 }} />Payments</span>}
      size="small"
      extra={
        <Flex align="center" gap={6}>
          <Button type="link" size="small" onClick={() => navigate('/app/payments')} 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>
      ) : data ? (
        <>
          <Flex gap={16} wrap="wrap" style={{ marginBottom: 8 }}>
            <Statistic
              title={<Text style={{ fontSize: 11 }}>Revenue</Text>}
              value={formatCents(data.totalRevenue)}
              valueStyle={{ fontSize: 18 }}
            />
            <Statistic
              title={<Text style={{ fontSize: 11 }}>MRR</Text>}
              value={formatCents(data.mrr)}
              valueStyle={{ fontSize: 18, color: data.mrr > 0 ? '#52c41a' : undefined }}
            />
            <Statistic
              title={<Text style={{ fontSize: 11 }}>Subscribers</Text>}
              value={data.activeSubscribers}
              valueStyle={{ fontSize: 18 }}
            />
            <Statistic
              title={<Text style={{ fontSize: 11 }}>Donations</Text>}
              value={data.donations?.totalDonations || 0}
              valueStyle={{ fontSize: 18 }}
            />
          </Flex>
          {recent.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 }}>Recent</Text>
              {recent.map(d => (
                <Flex key={d.id} justify="space-between" align="center" style={{ padding: '2px 0' }}>
                  <Text style={{ fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '55%' }}>
                    {d.isAnonymous ? 'Anonymous' : d.buyerName || d.buyerEmail}
                  </Text>
                  <Flex gap={4} align="center" style={{ flexShrink: 0 }}>
                    <Text strong style={{ fontSize: 12 }}>{formatCents(d.amountCAD)}</Text>
                    <Tag
                      color={d.status === 'COMPLETED' ? 'green' : d.status === 'PENDING' ? 'orange' : 'red'}
                      style={{ fontSize: 10, margin: 0, padding: '0 4px', lineHeight: '18px' }}
                    >
                      {d.status}
                    </Tag>
                  </Flex>
                </Flex>
              ))}
            </div>
          )}
        </>
      ) : (
        <Text type="secondary" style={{ fontSize: 13, display: 'block', padding: '8px 0' }}>No payment data</Text>
      )}
    </Card>
  );
}
