'use client';

import { useSponsorBilling } from "@/hooks/sponsor/useSponsorBilling";
import { SponsorBillingTemplate } from "@/templates/SponsorBillingTemplate";
import { Box } from "@/ui/primitives/Box";
import { Text } from "@/ui/Text";
import { Button } from "@/ui/Button";
import { DollarSign, AlertTriangle, Calendar, TrendingUp } from "lucide-react";

export default function SponsorBillingPage() {
  const { data: billingData, isLoading, error, retry } = useSponsorBilling('demo-sponsor-1');

  if (isLoading) {
    return (
      <Box maxWidth="5xl" mx="auto" py={8} px={4} display="flex" alignItems="center" justifyContent="center" minHeight="400px">
        <Box textAlign="center">
          <Box w="8" h="8" border borderTop={false} borderColor="border-primary-blue" rounded="full" animate="spin" mx="auto" mb={4} />
          <Text color="text-gray-400">Loading billing data...</Text>
        </Box>
      </Box>
    );
  }

  if (error || !billingData) {
    return (
      <Box maxWidth="5xl" mx="auto" py={8} px={4} display="flex" alignItems="center" justifyContent="center" minHeight="400px">
        <Box textAlign="center">
          <Text color="text-gray-400" block>{error?.message || 'No billing data available'}</Text>
          {error && (
            <Button variant="secondary" onClick={retry} mt={4}>
              Retry
            </Button>
          )}
        </Box>
      </Box>
    );
  }

  const handleSetDefault = (methodId: string) => {
    console.log('Setting default payment method:', methodId);
  };

  const handleRemoveMethod = (methodId: string) => {
    if (window.confirm('Remove this payment method?')) {
      console.log('Removing payment method:', methodId);
    }
  };

  const handleDownloadInvoice = (invoiceId: string) => {
    console.log('Downloading invoice:', invoiceId);
  };

  const billingStats = [
    {
      label: 'Total Spent',
      value: `$${billingData.stats.totalSpent.toFixed(2)}`,
      subValue: 'All time',
      icon: DollarSign,
      variant: 'success' as const,
    },
    {
      label: 'Pending Payments',
      value: `$${billingData.stats.pendingAmount.toFixed(2)}`,
      subValue: `${billingData.invoices.filter((i: any) => i.status === 'pending' || i.status === 'overdue').length} invoices`,
      icon: AlertTriangle,
      variant: (billingData.stats.pendingAmount > 0 ? 'warning' : 'default') as 'warning' | 'default',
    },
    {
      label: 'Next Payment',
      value: new Date(billingData.stats.nextPaymentDate).toLocaleDateString(),
      subValue: `$${billingData.stats.nextPaymentAmount.toFixed(2)}`,
      icon: Calendar,
      variant: 'info' as const,
    },
    {
      label: 'Monthly Average',
      value: `$${billingData.stats.averageMonthlySpend.toFixed(2)}`,
      subValue: 'Last 6 months',
      icon: TrendingUp,
      variant: 'default' as const,
    },
  ];

  const transactions = billingData.invoices.map((inv: any) => ({
    id: inv.id,
    date: inv.date,
    description: inv.description,
    amount: inv.totalAmount,
    status: inv.status as any,
    invoiceNumber: inv.invoiceNumber,
    type: inv.sponsorshipType,
  }));

  return (
    <SponsorBillingTemplate 
      viewData={billingData}
      billingStats={billingStats}
      transactions={transactions}
      onSetDefaultPaymentMethod={handleSetDefault}
      onDownloadInvoice={handleDownloadInvoice}
    />
  );
}
