import React, { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Loader2, FileDown } from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Label } from '@/components/ui/label';
import { format } from 'date-fns';

export default function HomeownerRequestExportDialog({ 
  open, 
  onOpenChange, 
  requests = [], 
  singleRequest = null,
  associations = [] 
}) {
  const [isExporting, setIsExporting] = useState(false);
  const [selectedAssociationFilter, setSelectedAssociationFilter] = useState('all');

  const handleExport = async () => {
    setIsExporting(true);
    try {
      let dataToExport = singleRequest ? [singleRequest] : requests;

      if (!singleRequest && selectedAssociationFilter !== 'all') {
        dataToExport = dataToExport.filter(req => req.association_id === selectedAssociationFilter);
      }

      if (dataToExport.length === 0) {
        alert("No data to export with current filters.");
        setIsExporting(false);
        return;
      }

      // Dynamic import for jsPDF to avoid bundle bloat
      const jsPDF = (await import('jspdf')).default;
      await import('jspdf-autotable');

      const doc = new jsPDF();
      let yPos = 20;

      doc.setFontSize(22);
      doc.setTextColor(44, 62, 80);
      doc.text("Homeowner Requests Report", 14, 20);
      
      doc.setDrawColor(200);
      doc.setLineWidth(0.5);
      doc.line(14, 25, 196, 25);

      yPos = 35;
      
      doc.setFontSize(10);
      doc.setTextColor(100);
      doc.text(`Generated: ${format(new Date(), 'MMM dd, yyyy HH:mm')}`, 14, yPos);
      yPos += 5;
      
      if (singleRequest) {
        doc.text(`Type: Detail Report`, 14, yPos);
      } else {
        const assocName = associations.find(c => c.id === selectedAssociationFilter)?.name || "All Associations";
        doc.text(`Association Filter: ${assocName}`, 14, yPos);
      }
      yPos += 15;

      for (const req of dataToExport) {
          if (yPos > 240) {
              doc.addPage();
              yPos = 20;
          }

          doc.setFillColor(240, 242, 245);
          doc.setDrawColor(210);
          doc.rect(14, yPos - 6, 182, 12, 'FD');
          
          doc.setFontSize(14);
          doc.setTextColor(0);
          doc.setFont("helvetica", "bold");
          const title = req.title || "Untitled Request";
          const displayTitle = title.length > 50 ? title.substring(0, 50) + "..." : title;
          doc.text(displayTitle, 17, yPos + 2);
          
          doc.setFontSize(10);
          const statusText = (req.status || 'open').toUpperCase();
          const statusWidth = doc.getTextWidth(statusText);
          doc.setTextColor(100);
          doc.text(statusText, 190 - statusWidth, yPos + 2);
          
          yPos += 15;

          doc.setTextColor(0);
          doc.setFontSize(10);
          doc.setFont("helvetica", "normal");
          const createdDate = format(new Date(req.created_at), 'MMM dd, yyyy');
          doc.text(`Submitted: ${createdDate}`, 17, yPos);
          yPos += 8;

          if (req.description) {
              doc.setFont("helvetica", "bold");
              doc.text("Description:", 17, yPos);
              yPos += 5;
              
              doc.setFont("helvetica", "normal");
              const splitDesc = doc.splitTextToSize(req.description, 175);
              doc.text(splitDesc, 17, yPos);
              yPos += (splitDesc.length * 5) + 10;
          }
      }

      const filename = singleRequest 
        ? `Request_${singleRequest.title.substring(0, 10).replace(/[^a-zA-Z0-9]/g, '_')}.pdf`
        : `Requests_Report_${format(new Date(), 'yyyy-MM-dd')}.pdf`;
      
      doc.save(filename);
      onOpenChange(false);
    } catch (error) {
      console.error("Export failed:", error);
      alert("Export failed. See console for details.");
    } finally {
      setIsExporting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{singleRequest ? 'Export Request Details' : 'Export Requests Report'}</DialogTitle>
          <DialogDescription>
            Generate a detailed PDF report.
          </DialogDescription>
        </DialogHeader>

        {!singleRequest && (
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="assoc-filter">Filter by Association</Label>
              <Select value={selectedAssociationFilter} onValueChange={setSelectedAssociationFilter}>
                <SelectTrigger id="assoc-filter">
                  <SelectValue placeholder="All Associations" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Associations</SelectItem>
                  {associations.map(assoc => (
                    <SelectItem key={assoc.id} value={assoc.id}>{assoc.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        )}

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={handleExport} disabled={isExporting}>
            {isExporting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <FileDown className="mr-2 h-4 w-4" />}
            Download PDF
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
