
import React, { useState } from 'react';
import { Download, Loader2 } from 'lucide-react';
import { format } from 'date-fns';
import Papa from 'papaparse';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { toESTDateDisplay } from '@/lib/timezoneUtils';
import { useToast } from '@/hooks/use-toast';

export function PaymentPlanExportDialog({ open, onOpenChange, paymentPlans }) {
  const [filterType, setFilterType] = useState('all');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [isExporting, setIsExporting] = useState(false);
  const { toast } = useToast();

  const getFilteredItems = () => {
    let items = [];
    paymentPlans.forEach(plan => {
      if (plan.items && Array.isArray(plan.items)) {
        plan.items.forEach(item => {
          items.push({ ...item, planTitle: plan.title, planStatus: plan.status, clientName: plan.client?.name || 'N/A' });
        });
      }
    });
    if (filterType === 'active') items = items.filter(i => i.planStatus === 'active');
    else if (filterType === 'custom' && startDate && endDate) {
      const start = new Date(startDate); const end = new Date(endDate);
      items = items.filter(i => { const d = new Date(i.due_date); return d >= start && d <= end; });
    }
    return items.sort((a, b) => new Date(a.due_date) - new Date(b.due_date));
  };

  const filteredItems = getFilteredItems();
  const totalAmount = filteredItems.reduce((sum, item) => sum + (parseFloat(item.amount) || 0), 0);

  const handleExport = async () => {
    try {
      setIsExporting(true);
      const csvData = filteredItems.map(item => ({
        'Payment Plan': item.planTitle, 'Association': item.clientName,
        'Due Date (EST)': toESTDateDisplay(item.due_date), 'Description': item.description,
        'Amount Due': parseFloat(item.amount).toFixed(2),
        'Status': item.received_date ? 'Paid' : 'Pending',
        'Received Date': item.received_date ? toESTDateDisplay(item.received_date) : '-'
      }));
      const csv = Papa.unparse(csvData);
      const { saveCsv } = await import('@/lib/saveFile');
      const saved = await saveCsv(csv, `payment_plans_export_${format(new Date(), 'yyyy-MM-dd')}.csv`);
      if (saved) {
        toast({ title: "Export Successful", description: `Exported ${filteredItems.length} records to CSV.` });
        onOpenChange(false);
      }
    } catch (error) {
      console.error("Export failed:", error);
      toast({ variant: "destructive", title: "Export Failed", description: "Error generating CSV." });
    } finally { setIsExporting(false); }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[700px]">
        <DialogHeader>
          <DialogTitle>Export Payment Plans</DialogTitle>
          <DialogDescription>Download a CSV report of payment plan items including EST dates.</DialogDescription>
        </DialogHeader>
        <div className="grid gap-4 py-4">
          <div className="space-y-3">
            <Label>Export Filters</Label>
            <RadioGroup value={filterType} onValueChange={setFilterType} className="flex flex-col space-y-1">
              <div className="flex items-center space-x-2"><RadioGroupItem value="all" id="all" /><Label htmlFor="all">All Plans</Label></div>
              <div className="flex items-center space-x-2"><RadioGroupItem value="active" id="active" /><Label htmlFor="active">Active Plans Only</Label></div>
              <div className="flex items-center space-x-2"><RadioGroupItem value="custom" id="custom" /><Label htmlFor="custom">Custom Date Range</Label></div>
            </RadioGroup>
          </div>
          {filterType === 'custom' && (
            <div className="grid grid-cols-2 gap-4 bg-muted/50 p-3 rounded-md border">
              <div className="space-y-1"><Label htmlFor="startDate">Start Date</Label><Input id="startDate" type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} /></div>
              <div className="space-y-1"><Label htmlFor="endDate">End Date</Label><Input id="endDate" type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} /></div>
            </div>
          )}
          <div className="space-y-2">
            <div className="flex justify-between items-center">
              <Label>Preview ({filteredItems.length} items)</Label>
              <span className="text-sm font-medium">Total: ${totalAmount.toFixed(2)}</span>
            </div>
            <div className="border rounded-md h-[200px] overflow-auto">
              <Table>
                <TableHeader><TableRow><TableHead>Due Date (EST)</TableHead><TableHead>Plan</TableHead><TableHead className="text-right">Amount</TableHead></TableRow></TableHeader>
                <TableBody>
                  {filteredItems.length === 0 ? (
                    <TableRow><TableCell colSpan={3} className="text-center text-muted-foreground py-8">No items found</TableCell></TableRow>
                  ) : filteredItems.map((item, idx) => (
                    <TableRow key={idx}>
                      <TableCell className="text-xs">{toESTDateDisplay(item.due_date)}</TableCell>
                      <TableCell className="text-xs truncate max-w-[200px]">{item.planTitle} - {item.description}</TableCell>
                      <TableCell className="text-xs text-right">${parseFloat(item.amount).toFixed(2)}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={handleExport} disabled={isExporting || filteredItems.length === 0}>
            {isExporting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Download className="mr-2 h-4 w-4" />}
            Export CSV
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
