import { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Table, Spin, App } from 'antd';
import { DollarOutlined, TeamOutlined, RiseOutlined, HeartOutlined } from '@ant-design/icons';
import { useOutletContext } from 'react-router-dom';
import { api } from '@/lib/api';
import type { PaymentDashboardStats, AppOutletContext } from '@/types/api';


export default function PaymentsDashboardPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const [stats, setStats] = useState<PaymentDashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const { message } = App.useApp();

  useEffect(() => {
    setPageHeader({ title: 'Payments Dashboard' });
    return () => setPageHeader(null);
  }, [setPageHeader]);

  useEffect(() => {
    api.get('/payments/admin/dashboard')
      .then(({ data }) => setStats(data))
      .catch(() => message.error('Failed to load dashboard'))
      .finally(() => setLoading(false));
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  if (loading) return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;

  const donationColumns = [
    { title: 'Date', dataIndex: 'createdAt', key: 'date', render: (v: string) => new Date(v).toLocaleDateString() },
    { title: 'Amount', dataIndex: 'amountCAD', key: 'amount', render: (v: number) => `$${(v / 100).toFixed(2)}` },
    { title: 'Donor', dataIndex: 'buyerEmail', key: 'donor' },
    { title: 'Status', dataIndex: 'status', key: 'status' },
  ];

  return (
    <div>
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="Active Subscribers"
              value={stats?.activeSubscribers || 0}
              prefix={<TeamOutlined />}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="Monthly Recurring Revenue"
              value={(stats?.mrr || 0) / 100}
              precision={2}
              prefix={<RiseOutlined />}
              suffix="CAD"
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="Total Revenue"
              value={(stats?.totalRevenue || 0) / 100}
              precision={2}
              prefix={<DollarOutlined />}
              suffix="CAD"
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <Statistic
              title="Total Donations"
              value={stats?.donations?.totalDonations || 0}
              prefix={<HeartOutlined />}
              suffix={`($${((stats?.donations?.totalAmount || 0) / 100).toFixed(2)})`}
            />
          </Card>
        </Col>
      </Row>

      <Card title="Recent Donations" style={{ marginBottom: 24 }}>
        <Table
          dataSource={stats?.donations?.recentDonations || []}
          columns={donationColumns}
          rowKey="id"
          pagination={false}
          scroll={{ x: 'max-content' }}
          size="small"
        />
      </Card>
    </div>
  );
}
