import { useState, useEffect, useCallback } from 'react';
import { DollarSign, Tag, Megaphone, CreditCard } from 'lucide-react';
import { StatCard } from '../../components/ui/StatCard';
import { DataTable } from '../../components/ui/DataTable';
import { Badge } from '../../components/ui/Badge';
import { api } from '../../api/client';

interface Payment {
  id: string;
  amount: number;
  status: string;
  type: string;
  description?: string;
  createdAt: string;
  user: { id: string; fullName: string };
  listing: { id: string; title: string };
}

interface RevenueBreakdown {
  listingFees: { total: number; count: number };
  commissions: { total: number; count: number };
  promotions: { total: number; count: number };
  subscriptions: { total: number; count: number };
}

export function AdminPaymentsPage() {
  const [payments, setPayments] = useState<Payment[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [revenue, setRevenue] = useState<RevenueBreakdown | null>(null);

  const fetchPayments = useCallback(async () => {
    const params = new URLSearchParams({ page: String(page), pageSize: '20' });
    const res = await api.get<{ data: Payment[]; total: number }>(`/admin/payments?${params}`);
    setPayments(res.data);
    setTotal(res.total);
  }, [page]);

  useEffect(() => {
    fetchPayments();
    api.get<RevenueBreakdown>('/admin/payments/revenue').then(setRevenue).catch(() => {});
  }, [fetchPayments]);

  return (
    <div>
      <h1 className="text-2xl font-bold text-gray-900 mb-6">Payments</h1>

      {revenue && (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
          <StatCard icon={DollarSign} label="Listing Fees" value={`$${revenue.listingFees.total.toFixed(2)}`} color="green" />
          <StatCard icon={Tag} label="Commissions" value={`$${revenue.commissions.total.toFixed(2)}`} color="blue" />
          <StatCard icon={Megaphone} label="Promotions" value={`$${revenue.promotions.total.toFixed(2)}`} color="yellow" />
          <StatCard icon={CreditCard} label="Subscriptions" value={`$${revenue.subscriptions.total.toFixed(2)}`} color="pink" />
        </div>
      )}

      <DataTable
        columns={[
          { key: 'user', header: 'User', render: (p: Payment) => p.user.fullName },
          { key: 'listing', header: 'Listing', render: (p: Payment) => <span className="truncate max-w-xs block">{p.listing.title}</span> },
          { key: 'amount', header: 'Amount', render: (p: Payment) => `$${p.amount.toFixed(2)}` },
          { key: 'type', header: 'Type', render: (p: Payment) => <Badge variant="default" size="sm">{p.type.replace('_', ' ')}</Badge> },
          {
            key: 'status',
            header: 'Status',
            render: (p: Payment) => (
              <Badge variant={p.status === 'COMPLETED' ? 'success' : p.status === 'FAILED' ? 'error' : 'warning'} size="sm">
                {p.status}
              </Badge>
            ),
          },
          { key: 'createdAt', header: 'Date', render: (p: Payment) => new Date(p.createdAt).toLocaleDateString() },
        ]}
        data={payments}
        total={total}
        page={page}
        pageSize={20}
        onPageChange={setPage}
      />
    </div>
  );
}
