import React, { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { jsPDF } from 'jspdf';
import { FileText, Loader2 } from 'lucide-react';
import { supabase } from '@/lib/customSupabaseClient';
import { useToast } from '@/components/ui/use-toast';

export function ViolationReportGenerator({ onExport, defaultClientId }) {
  const { toast } = useToast();
  const [isOpen, setIsOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState({
    startDate: '',
    endDate: '',
    status: 'all'
  });

  const loadImage = (url) => {
      return new Promise((resolve) => {
        const img = new Image();
        img.crossOrigin = 'Anonymous';
        img.onload = () => {
          const canvas = document.createElement('canvas');
          canvas.width = img.width;
          canvas.height = img.height;
          const ctx = canvas.getContext('2d');
          ctx.drawImage(img, 0, 0);
          resolve({ dataURL: canvas.toDataURL('image/jpeg', 0.7), width: img.width, height: img.height });
        };
        img.onerror = () => resolve(null);
        img.src = url;
      });
  };

  const generateReport = async () => {
    setLoading(true);
    try {
      let query = supabase.from('violations')
        .select(`*, associations(name), owners(first_name, last_name, property_address, status)`)
        .neq('owners.status', 'archived')
        .order('violation_date', { ascending: false });

      if (defaultClientId) query = query.eq('association_id', defaultClientId);
      if (filters.status !== 'all') query = query.eq('status', filters.status);
      if (filters.startDate) query = query.gte('violation_date', filters.startDate);
      if (filters.endDate) query = query.lte('violation_date', filters.endDate);

      const { data: violations, error } = await query;
      if (error) throw error;

      if (!violations.length) {
        toast({ title: "No Violations Found", description: "Try adjusting your filters." });
        setLoading(false);
        return;
      }

      const doc = new jsPDF();
      const pageWidth = doc.internal.pageSize.getWidth();
      const pageHeight = doc.internal.pageSize.getHeight();
      const margin = 14;
      const contentWidth = pageWidth - (margin * 2);
      let y = 20;

      // Header
      doc.setFillColor(51, 65, 85);
      doc.rect(0, 0, pageWidth, 25, 'F');
      doc.setTextColor(255, 255, 255);
      doc.setFontSize(18);
      doc.setFont("helvetica", "bold");
      doc.text("Violation Summary Report", margin, 17);
      
      y = 40;

      for (let i = 0; i < violations.length; i++) {
         const v = violations[i];
         
         // Page break check
         if (y + 80 > pageHeight - margin) {
             doc.addPage();
             y = 20;
         }

         // Card-like Container
         doc.setDrawColor(226, 232, 240);
         doc.setFillColor(248, 250, 252);
         doc.roundedRect(margin, y, contentWidth, 70, 2, 2, 'FD');
         
         // Left Side: Text Details
         doc.setTextColor(51, 65, 85);
         doc.setFontSize(12);
         doc.setFont("helvetica", "bold");
         doc.text(v.violation_type || 'Violation', margin + 5, y + 10);
         
         doc.setFontSize(10);
         doc.setFont("helvetica", "normal");
         doc.setTextColor(100);
          const ownerName = v.allOwnerNames || `${v.owners?.first_name || ''} ${v.owners?.last_name || ''}`.trim() || 'Unknown Owner';
           const address = v.owners?.property_address || v.address || 'Unknown Address';
         doc.text(`${ownerName} — ${address}`, margin + 5, y + 18);
         
         // Status Badge simulation
         const statusColor = v.status === 'resolved' ? [22, 163, 74] : [220, 38, 38];
         doc.setTextColor(...statusColor);
         doc.setFont("helvetica", "bold");
         doc.text(v.status.toUpperCase(), margin + 5, y + 26);
         
         // Details grid
         doc.setTextColor(51, 65, 85);
         doc.setFont("helvetica", "normal");
         doc.text(`Stage: ${v.stage?.replace('_', ' ') || '-'}`, margin + 5, y + 36);
         const parseSafe = (ds) => ds && /^\d{4}-\d{2}-\d{2}$/.test(ds) ? new Date(`${ds}T12:00:00`) : new Date(ds);
         doc.text(`Date: ${parseSafe(v.violation_date || v.created_at).toLocaleDateString()}`, margin + 5, y + 44);
         doc.text(`Due: ${v.due_date ? parseSafe(v.due_date).toLocaleDateString() : '-'}`, margin + 5, y + 52);
         
         // Photo Thumbnail
         if (v.photo_url) {
             const imgData = await loadImage(v.photo_url);
             if (imgData) {
                 const thumbH = 60;
                 const thumbW = (imgData.width / imgData.height) * thumbH;
                 // Keep aspect ratio but limit width
                 const finalW = Math.min(thumbW, 80);
                 const finalH = (imgData.height / imgData.width) * finalW;
                 
                 doc.addImage(imgData.dataURL, 'JPEG', pageWidth - margin - finalW - 5, y + 5, finalW, finalH);
             }
         }

         y += 75;
      }

      doc.save('Violation_Report.pdf');
      toast({ title: "Report Generated", description: "Your PDF report is ready." });
      setIsOpen(false);

    } catch (err) {
      console.error(err);
      toast({ variant: 'destructive', title: "Error", description: "Failed to generate report." });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogTrigger asChild>
        <Button variant="outline"><FileText className="w-4 h-4 mr-2" /> Generate Report</Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Generate Violation Report</DialogTitle>
        </DialogHeader>
        <div className="space-y-4 py-4">
           <div className="grid grid-cols-2 gap-4">
               <div className="space-y-2">
                   <Label>Start Date</Label>
                   <Input type="date" value={filters.startDate} onChange={(e) => setFilters({...filters, startDate: e.target.value})} />
               </div>
               <div className="space-y-2">
                   <Label>End Date</Label>
                   <Input type="date" value={filters.endDate} onChange={(e) => setFilters({...filters, endDate: e.target.value})} />
               </div>
           </div>
           <div className="space-y-2">
               <Label>Status</Label>
               <Select value={filters.status} onValueChange={(val) => setFilters({...filters, status: val})}>
                   <SelectTrigger><SelectValue /></SelectTrigger>
                   <SelectContent>
                       <SelectItem value="all">All Statuses</SelectItem>
                       <SelectItem value="open">Open</SelectItem>
                       <SelectItem value="resolved">Resolved</SelectItem>
                       <SelectItem value="recommended_for_fining">Recommended for Fining</SelectItem>
                       <SelectItem value="fined">Fined</SelectItem>
                   </SelectContent>
               </Select>
           </div>
           <Button onClick={generateReport} disabled={loading} className="w-full">
               {loading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />} Download PDF Report
           </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}