import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { useToast } from '@/hooks/use-toast';
import { FileDown, Loader2, Trash2, Settings, Database, AlertTriangle, FolderDown } from 'lucide-react';
import { jsPDF } from 'jspdf';
import 'jspdf-autotable';
import { supabase } from '@/integrations/supabase/client';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import { Badge } from '@/components/ui/badge';
import { getNoticeContent } from '@/lib/noticeContentUtils';
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { loadNotoSymbolsFont, registerNotoSymbolsFont } from '@/lib/fontManager';
import { SaveToDocumentsDialog } from '@/components/SaveToDocumentsDialog';
import PdfStylingControls from '@/components/forms/PdfStylingControls';
import { buildLedgerAccountBreakdown } from '@/lib/unitLedgerAccountBreakdown';
import { formatMailingAddress } from '@/lib/formatMailingAddress';
import { combineOwnerNames } from '@/lib/ownerAddressUtils';
import { Checkbox } from '@/components/ui/checkbox';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { ScrollArea } from '@/components/ui/scroll-area';

export default function BatchAssessmentForm() {
  const { toast } = useToast();
  const [associations, setAssociations] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selectedAssociationId, setSelectedAssociationId] = useState('');
  const [showSaveDocsDialog, setShowSaveDocsDialog] = useState(false);

  const [noticeType, setNoticeType] = useState('reminder');
  const [pdfConfig, setPdfConfig] = useState({
    font: 'helvetica',
    fontSize: '9',
    textAlign: 'left'
  });

  // Selection dialog state
  const [showSelectionDialog, setShowSelectionDialog] = useState(false);
  const [candidateItems, setCandidateItems] = useState([]);
  const [selectedCandidateIds, setSelectedCandidateIds] = useState(new Set());

  const getDefaultDueDate = () => {
    const d = new Date();
    d.setDate(d.getDate() + 30);
    return d.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
  };

  const [globalSettings, setGlobalSettings] = useState({
    date: new Date().toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }),
    dueDate: getDefaultDueDate(),
    interestRate: '12.00',
    managementCompany: 'Avria Community Management, LLC',
    managementEmail: '',
    managementPhone: '(321) 405-2449',
    managementWebsite: '',
    associationName: '',
    paymentAddressLine1: 'P.O. Box 560060',
    paymentAddressLine2: 'Rockledge, Florida 32956',
    noticeLogo: '',
    footerLogo: ''
  });

  const [batchData, setBatchData] = useState([]);

  useEffect(() => {
    fetchAssociations();
  }, []);

  const fetchAssociations = async () => {
    const { data, error } = await supabase.from('associations').select('id, name, email, phone, website, logo_url');
    if (!error) setAssociations(data || []);
  };

  const handleAssociationChange = (associationId) => {
    setSelectedAssociationId(associationId);
    setBatchData([]);
    const assoc = associations.find(c => c.id === associationId);
    if (assoc) {
      setGlobalSettings(prev => ({
        ...prev,
        associationName: assoc.name,
        managementEmail: assoc.email || prev.managementEmail,
        managementPhone: assoc.phone || prev.managementPhone,
        managementWebsite: assoc.website || prev.managementWebsite,
        noticeLogo: assoc.logo_url || ''
      }));
    }
  };

  const handleGlobalChange = (e) => {
    const { name, value } = e.target;
    setGlobalSettings(prev => ({ ...prev, [name]: value }));
  };

  const removeItem = (id) => {
    setBatchData(prev => prev.filter(item => item.id !== id));
  };

  const clearBatch = () => {
    if(window.confirm('Are you sure you want to clear the entire batch?')) {
        setBatchData([]);
    }
  };

  const buildBatchItems = (allOwners, allLedger) => {
    const ledgerByOwner = {};
    allLedger.forEach(e => {
      if (!ledgerByOwner[e.owner_id]) ledgerByOwner[e.owner_id] = [];
      ledgerByOwner[e.owner_id].push(e);
    });

    const unitGroups = new Map();
    let noUnitIdx = 0;
    allOwners.forEach(owner => {
      const key = owner.unit_id || `__no_unit_${noUnitIdx++}`;
      if (!unitGroups.has(key)) unitGroups.set(key, []);
      unitGroups.get(key).push(owner);
    });

    const items = [];
    let itemIdx = 0;
    for (const [, groupOwners] of unitGroups) {
      let combinedEntries = [];
      groupOwners.forEach(owner => {
        const entries = ledgerByOwner[owner.id] || [];
        combinedEntries = combinedEntries.concat(entries);
      });
      if (combinedEntries.length === 0) continue;

      const { rows: breakdownRows, totals } = buildLedgerAccountBreakdown(combinedEntries);
      if (totals.openBalance <= 0) continue;

      const assessments = breakdownRows.find(r => r.type === 'assessment')?.openBalance || 0;
      const lateFees = breakdownRows.find(r => r.type === 'late_fee')?.openBalance || 0;
      const interest = breakdownRows.find(r => r.type === 'interest')?.openBalance || 0;
      const otherCharges = breakdownRows
        .filter(r => !['assessment', 'late_fee', 'interest'].includes(r.type))
        .reduce((sum, r) => sum + (r.openBalance > 0 ? r.openBalance : 0), 0);

      const ownerName = combineOwnerNames(groupOwners);
      const primaryOwner = groupOwners[0];
      const { full: formattedAddress } = formatMailingAddress(primaryOwner, ownerName);
      const primaryAddress = primaryOwner.mailing_address || primaryOwner.property_address || '';

      const alternates = [];
      const seenAddr = new Set([primaryAddress.trim().toLowerCase()]);
      groupOwners.forEach(owner => {
        if (owner.alternate_address_1?.trim() && !seenAddr.has(owner.alternate_address_1.trim().toLowerCase())) {
          seenAddr.add(owner.alternate_address_1.trim().toLowerCase());
          alternates.push(owner.alternate_address_1.trim());
        }
        if (owner.alternate_address_2?.trim() && !seenAddr.has(owner.alternate_address_2.trim().toLowerCase())) {
          seenAddr.add(owner.alternate_address_2.trim().toLowerCase());
          alternates.push(owner.alternate_address_2.trim());
        }
      });

      const lineItems = [
        { description: 'Assessments', amount: assessments > 0 ? assessments.toFixed(2) : '0.00' },
        { description: 'Late Fees', amount: lateFees > 0 ? lateFees.toFixed(2) : '0.00' },
        { description: 'Interest', amount: interest > 0 ? interest.toFixed(2) : '0.00' }
      ];
      if (otherCharges > 0) {
        lineItems.push({ description: 'Other Charges', amount: otherCharges.toFixed(2) });
      }

      items.push({
        id: Date.now() + itemIdx++ + Math.random(),
        ownerName,
        propertyAddress: primaryOwner.property_address || '',
        accountNo: primaryOwner.units?.account_number || primaryOwner.account_number || '',
        primaryAddress,
        alternateAddresses: alternates,
        items: lineItems,
        hiddenItems: [],
        totalDue: totals.openBalance
      });
    }

    return items;
  };

  const loadFromDatabase = async () => {
    if (!selectedAssociationId) {
      toast({ variant: "destructive", title: "Selection Required", description: "Please select an association first." });
      return;
    }

    setLoading(true);
    try {
      // Fetch ALL active owners for the association
      const CHUNK = 100;
      const PAGE = 1000;
      
      let allOwners = [];
      let from = 0;
      let keepGoing = true;
      while (keepGoing) {
        const { data, error } = await supabase
          .from('owners')
          .select('*')
          .eq('association_id', selectedAssociationId)
          .neq('status', 'archived')
          .range(from, from + PAGE - 1);
        if (error) throw error;
        allOwners = allOwners.concat(data || []);
        keepGoing = (data || []).length === PAGE;
        from += PAGE;
      }

      if (allOwners.length === 0) {
        toast({ title: "No Owners Found", description: "No active owners found for this association." });
        setLoading(false);
        return;
      }

      const ownerIds = allOwners.map(o => o.id);

      // Fetch all ledger entries (paginated + chunked)
      let allLedger = [];
      for (let ci = 0; ci < ownerIds.length; ci += CHUNK) {
        const chunk = ownerIds.slice(ci, ci + CHUNK);
        let lFrom = 0;
        let lKeep = true;
        while (lKeep) {
          const { data: batch, error: lErr } = await supabase
            .from('owner_ledger_entries')
            .select('*')
            .in('owner_id', chunk)
            .range(lFrom, lFrom + PAGE - 1);
          if (lErr) throw lErr;
          allLedger = allLedger.concat(batch || []);
          lKeep = (batch || []).length === PAGE;
          lFrom += PAGE;
        }
      }

      const candidates = buildBatchItems(allOwners, allLedger);

      if (candidates.length === 0) {
        toast({ title: "No Outstanding Balances", description: "No accounts with outstanding balances found." });
        setLoading(false);
        return;
      }

      // Sort by total due descending
      candidates.sort((a, b) => b.totalDue - a.totalDue);

      // Pre-select all
      setCandidateItems(candidates);
      setSelectedCandidateIds(new Set(candidates.map(c => c.id)));
      setShowSelectionDialog(true);

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

  const handleConfirmSelection = () => {
    const selected = candidateItems.filter(c => selectedCandidateIds.has(c.id));
    if (selected.length === 0) {
      toast({ variant: "destructive", title: "No Selection", description: "Please select at least one account." });
      return;
    }
    setBatchData(prev => [...prev, ...selected]);
    setShowSelectionDialog(false);
    setCandidateItems([]);
    setSelectedCandidateIds(new Set());
    toast({ title: "Loaded", description: `Added ${selected.length} accounts to batch.` });
  };

  const toggleCandidate = (id) => {
    setSelectedCandidateIds(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const toggleAllCandidates = () => {
    if (selectedCandidateIds.size === candidateItems.length) {
      setSelectedCandidateIds(new Set());
    } else {
      setSelectedCandidateIds(new Set(candidateItems.map(c => c.id)));
    }
  };

  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);
        try {
            resolve({ dataURL: canvas.toDataURL('image/png'), width: img.width, height: img.height });
        } catch (e) { resolve(null); }
      };
      img.onerror = () => resolve(null);
      img.src = url;
    });
  };

  const getTotal = (items, hiddenItems = []) => {
    const visibleTotal = items.reduce((acc, item) => acc + (parseFloat(item.amount.replace(/,/g, '')) || 0), 0);
    const hiddenTotal = hiddenItems.reduce((acc, item) => acc + (parseFloat(item.amount.replace(/,/g, '')) || 0), 0);
    return (visibleTotal + hiddenTotal).toFixed(2);
  };
  
  const calculateTotalLetters = () => {
      return batchData.reduce((acc, item) => acc + 1 + (item.alternateAddresses?.length || 0), 0);
  };

  const generateBatchPDF = async (action = 'download') => {
    if (batchData.length === 0) {
      toast({ variant: "destructive", title: "Empty Batch", description: "No records to generate." });
      return null;
    }

    setLoading(true);
    try {
      await loadNotoSymbolsFont();
      const doc = new jsPDF({ orientation: 'portrait', unit: 'pt', format: 'letter' });
      registerNotoSymbolsFont(doc);

      const pageWidth = doc.internal.pageSize.getWidth();
      const pageHeight = doc.internal.pageSize.getHeight();
      const margin = 54;
      const returnAddressX = 38; 
      const returnAddressY = 60; 
      const baseFontSize = parseInt(pdfConfig.fontSize) || 9;
      const baseFont = pdfConfig.font || "helvetica";
      const textAlign = pdfConfig.textAlign || 'left';

      let headerLogoData = null;
      if (globalSettings.noticeLogo) headerLogoData = await loadImage(globalSettings.noticeLogo);
      let footerLogoData = null;
      if (globalSettings.footerLogo) footerLogoData = await loadImage(globalSettings.footerLogo);

      const alignRight = (text, y, fontSize = baseFontSize, font = baseFont, style = "normal") => {
            doc.setFont(font, style);
            doc.setFontSize(fontSize);
            const w = doc.getTextWidth(text);
            doc.text(text, pageWidth - margin - w, y);
      };

      const paragraphGap = baseFontSize * 0.8;

      const writeTextBlock = (text, startY, isBold = false) => {
          doc.setFont(baseFont, isBold ? "bold" : "normal");
          doc.setFontSize(baseFontSize);
          const maxLineWidth = pageWidth - (margin * 2);
          const lineHeight = baseFontSize * 1.3;
          const lines = doc.splitTextToSize(text, maxLineWidth);
          let y = startY;
          if (y + (lines.length * lineHeight) > pageHeight - 120) {
            doc.addPage();
            y = margin + 30;
          }
          doc.text(text, margin, y, { maxWidth: maxLineWidth, align: textAlign, lineHeightFactor: 1.3 });
          return y + (lines.length * lineHeight) + 12 + paragraphGap;
      };

      // Expand batch: Primary + Alternates
      const printQueue = [];
      batchData.forEach(item => {
          printQueue.push({ ...item, recipientName: item.ownerName, recipientAddress: item.primaryAddress, isAlternate: false });
          if (item.alternateAddresses && item.alternateAddresses.length > 0) {
              item.alternateAddresses.forEach(altAddr => {
                  printQueue.push({ ...item, recipientName: globalSettings.associationName, recipientAddress: altAddr, isAlternate: true });
              });
          }
      });

      const content = getNoticeContent(noticeType, globalSettings);

      for (let i = 0; i < printQueue.length; i++) {
        if (i > 0) doc.addPage();
        const startPage = doc.internal.getNumberOfPages();
        const letterData = printQueue[i];
        
        doc.setFont(baseFont, "normal");
        doc.setFontSize(baseFontSize);
        doc.setTextColor(0);

        // --- 1. HEADER ---
        let currentY = returnAddressY;
        [globalSettings.associationName, "c/o " + globalSettings.managementCompany, globalSettings.paymentAddressLine1, globalSettings.paymentAddressLine2].forEach(line => {
            if (line) { doc.text(line, returnAddressX, currentY); currentY += 12; }
        });

        if (headerLogoData) {
            const { dataURL, width, height } = headerLogoData;
            const maxLogoW = 200; const maxLogoH = 50;
            let logoW = maxLogoW; let logoH = logoW * (width / height);
            if (logoH > maxLogoH) { logoH = maxLogoH; logoW = logoH * (width / height); }
            doc.addImage(dataURL, 'PNG', pageWidth - margin - logoW, margin - 15, logoW, logoH);
        }

        // --- 2. RECIPIENT ---
        let addressBlockY = 175; 
        alignRight(globalSettings.date, addressBlockY, baseFontSize, baseFont, "bold");

        let addrY = addressBlockY;
        doc.setFont(baseFont, "normal");
        doc.setFontSize(baseFontSize);

        if (letterData.recipientName) { doc.text(letterData.recipientName, margin, addrY); addrY += 12; }
        if (letterData.recipientAddress) {
            letterData.recipientAddress.split('\n').map(l => l.trim()).filter(l => l).forEach(line => {
                doc.text(line, margin, addrY); addrY += 12;
            });
        }

        currentY = Math.max(addrY + 30, 240);

        // --- 3. BODY ---
        doc.setFont(baseFont, "bold");
        doc.setFontSize(11);
        doc.text(content.title, pageWidth / 2, currentY, { align: 'center' });
        const titleW = doc.getTextWidth(content.title);
        doc.setLineWidth(1);
        doc.line((pageWidth - titleW)/2, currentY + 2, (pageWidth + titleW)/2, currentY + 2);
        currentY += 24;

        doc.setFont(baseFont, "normal");
        doc.setFontSize(baseFontSize);
        doc.text(`Dear ${letterData.ownerName}:`, margin, currentY);
        currentY += 24;

        currentY = writeTextBlock(content.intro, currentY, false, true);
        currentY += 12;

        const totalDue = getTotal(letterData.items, letterData.hiddenItems);
        
        // --- FINANCIAL BREAKDOWN TABLE ---
        const tableIndent = margin + 40;
        const dollarSignX = pageWidth - margin - 120;
        const amountRightEdge = pageWidth - margin - 60;
        
        doc.setFont(baseFont, "normal");
        doc.setFontSize(baseFontSize);
        
        letterData.items.forEach(item => {
            const amt = parseFloat(item.amount.replace(/,/g, '') || '0');
            if (amt > 0) {
                doc.setFont(baseFont, "normal");
                doc.setFontSize(baseFontSize);
                doc.text(`${item.description}:`, tableIndent, currentY);
                doc.text("$", dollarSignX, currentY);
                doc.text(amt.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }), amountRightEdge, currentY, { align: 'right' });
                currentY += 15;
            }
        });
        
        currentY += 5;
        doc.setLineWidth(0.5);
        doc.line(tableIndent, currentY, amountRightEdge + 10, currentY);
        currentY += 15;
        
        doc.setFont(baseFont, "bold");
        doc.setFontSize(baseFontSize);
        doc.text("TOTAL AMOUNT DUE:", tableIndent, currentY);
        doc.text("$", dollarSignX, currentY);
        const fmtTotal = parseFloat(totalDue.replace(/,/g, '') || '0').toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        doc.text(fmtTotal, amountRightEdge, currentY, { align: 'right' });
        doc.setFont(baseFont, "normal");
        currentY += 24;

        currentY = writeTextBlock(content.consequences, currentY, false, true);
        currentY += 12;
        currentY = writeTextBlock(content.contact, currentY, false, true);
        currentY += 12;
        currentY = writeTextBlock(content.instructions, currentY, false, true);
        currentY += 24;

        if (currentY + 60 > pageHeight - 120) { doc.addPage(); currentY = margin + 30; }
        doc.text("Sincerely,", margin, currentY); currentY += 25; 
        doc.text(globalSettings.managementCompany, margin, currentY); currentY += 11;
        doc.text(`Managing Agent for ${globalSettings.associationName}`, margin, currentY);
        
        // --- FOOTER ---
        const endPage = doc.internal.getNumberOfPages();
        for (let j = startPage; j <= endPage; j++) {
            doc.setPage(j);
            const footerLineY = pageHeight - 50;
            
            if (footerLogoData) {
                const { dataURL, width, height } = footerLogoData;
                const fLogoH = 25; const fLogoW = fLogoH * (width / height);
                doc.addImage(dataURL, 'PNG', (pageWidth - fLogoW) / 2, footerLineY - fLogoH - 5, fLogoW, fLogoH);
            } else {
                doc.setFont("helvetica", "bold");
                doc.setFontSize(9);
                const txt = "ACM";
                doc.text(txt, (pageWidth - doc.getTextWidth(txt))/2, footerLineY - 15);
            }

            doc.setDrawColor(0);
            doc.setLineWidth(0.5);
            doc.line(margin, footerLineY, pageWidth - margin, footerLineY);
            
            const infoY = footerLineY + 15;
            doc.setFont("helvetica", "normal");
            doc.setFontSize(8); 
            doc.text(`Phone: ${globalSettings.managementPhone}`, margin, infoY);
            doc.text(globalSettings.managementEmail, (pageWidth - doc.getTextWidth(globalSettings.managementEmail)) / 2, infoY);
            const webW = doc.getTextWidth(globalSettings.managementWebsite);
            doc.text(globalSettings.managementWebsite, pageWidth - margin - webW, infoY);
            doc.text(`${j - startPage + 1}`, (pageWidth - doc.getTextWidth(`${j - startPage + 1}`)) / 2, pageHeight - 20); 
        }
      }

      if (action === 'blob') {
          return doc.output('blob');
      } else {
          const fileName = `Batch_${noticeType === 'final' ? 'Final' : 'Reminder'}_Notices_${new Date().toISOString().split('T')[0]}.pdf`;
          doc.save(fileName);
          toast({ title: "Success", description: `Generated PDF with ${printQueue.length} letters.` });
      }

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

  const handleSaveToDocuments = async (metadata) => {
    try {
        const blob = await generateBatchPDF('blob');
        if (!blob) throw new Error("Failed to generate PDF blob.");

        const { data: userData } = await supabase.auth.getUser();
        if (!userData?.user) throw new Error("Not authenticated");

        const safeName = metadata.name.replace(/[^a-z0-9]/gi, '_').toLowerCase();
        const fileName = `${Date.now()}-${safeName}.pdf`;
        const filePath = `${userData.user.id}/${fileName}`;

        const { error: uploadError } = await supabase.storage
            .from('files')
            .upload(filePath, blob, { contentType: 'application/pdf' });
        if (uploadError) throw uploadError;

        toast({ title: 'Success', description: 'Document saved successfully.' });
        return { blob };
    } catch (err) {
        console.error(err);
        toast({ variant: 'destructive', title: 'Error saving document', description: err.message });
        throw err;
    }
  };

  return (
    <div className="max-w-6xl mx-auto space-y-6">
      
      {/* Configuration Card */}
      <Card>
        <CardHeader className="bg-muted/50 border-b">
          <div className="flex justify-between items-center">
             <CardTitle className="flex items-center gap-2">
                <Settings className="w-5 h-5 text-primary" />
                Batch Configuration
             </CardTitle>
             <Button onClick={loadFromDatabase} variant="outline" disabled={loading}>
                {loading ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <Database className="w-4 h-4 mr-2" />}
                Load from DB
             </Button>
          </div>
        </CardHeader>
        <CardContent className="p-6 space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <Label>Select Association</Label>
                  <Select onValueChange={handleAssociationChange} value={selectedAssociationId}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select Association" />
                    </SelectTrigger>
                    <SelectContent>
                      {associations.map((assoc) => (
                        <SelectItem key={assoc.id} value={assoc.id}>{assoc.name}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="grid grid-cols-2 gap-4">
                    <div>
                        <Label>Letter Date</Label>
                        <Input name="date" value={globalSettings.date} onChange={handleGlobalChange} />
                    </div>
                    <div>
                        <Label>Due Date</Label>
                        <Input name="dueDate" value={globalSettings.dueDate} onChange={handleGlobalChange} />
                    </div>
                </div>
            </div>

            <div className="space-y-3 bg-muted/50 p-4 rounded-lg border">
                <Label className="text-foreground font-medium">Notice Type</Label>
                <RadioGroup defaultValue="reminder" value={noticeType} onValueChange={setNoticeType} className="flex gap-6">
                    <div className="flex items-center space-x-2">
                        <RadioGroupItem value="reminder" id="r-reminder" />
                        <Label htmlFor="r-reminder" className="font-normal cursor-pointer">Reminder Notice</Label>
                    </div>
                    <div className="flex items-center space-x-2">
                        <RadioGroupItem value="final" id="r-final" />
                        <Label htmlFor="r-final" className="font-medium cursor-pointer text-destructive flex items-center gap-2">
                            Final Notice
                            {noticeType === 'final' && <AlertTriangle className="w-4 h-4" />}
                        </Label>
                    </div>
                </RadioGroup>
                <p className="text-xs text-muted-foreground mt-1">
                    {noticeType === 'final' 
                        ? 'Includes firm language regarding collections, legal action, and credit reporting.' 
                        : 'Standard friendly reminder about past due balance.'}
                </p>
            </div>

            {/* PDF Styling */}
            <PdfStylingControls pdfConfig={pdfConfig} onChange={setPdfConfig} />

            <Accordion type="single" collapsible className="w-full bg-muted/50 rounded-lg border">
                <AccordionItem value="details" className="border-none">
                    <AccordionTrigger className="px-4 py-3 text-muted-foreground font-medium hover:no-underline">
                        Advanced Settings (Contact & Logos)
                    </AccordionTrigger>
                    <AccordionContent className="px-4 pb-4 pt-2 bg-background rounded-b-lg border-t">
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                             <div className="space-y-2"><Label>Mgmt Company Name</Label><Input name="managementCompany" value={globalSettings.managementCompany} onChange={handleGlobalChange} /></div>
                             <div className="space-y-2"><Label>Mgmt Email</Label><Input name="managementEmail" value={globalSettings.managementEmail} onChange={handleGlobalChange} /></div>
                             <div className="space-y-2"><Label>Mgmt Phone</Label><Input name="managementPhone" value={globalSettings.managementPhone} onChange={handleGlobalChange} /></div>
                             <div className="space-y-2"><Label>Logo URL</Label><Input name="noticeLogo" value={globalSettings.noticeLogo} onChange={handleGlobalChange} /></div>
                             <div className="space-y-2"><Label>Footer Logo URL</Label><Input name="footerLogo" value={globalSettings.footerLogo} onChange={handleGlobalChange} /></div>
                        </div>
                    </AccordionContent>
                </AccordionItem>
            </Accordion>
        </CardContent>
      </Card>

      {/* Batch Data Table */}
      <Card>
          <CardHeader>
              <div className="flex justify-between items-center">
                  <div className="flex items-center gap-2">
                      <CardTitle>Batch Queue ({batchData.length})</CardTitle>
                      {batchData.length > 0 && (
                          <>
                            <Badge variant="secondary" className="ml-2">
                                Total Letters: {calculateTotalLetters()}
                            </Badge>
                            <Button variant="ghost" size="sm" onClick={clearBatch} className="text-destructive hover:text-destructive text-xs h-6 px-2 ml-2">
                                Clear All
                            </Button>
                          </>
                      )}
                  </div>
                  <div className="flex gap-2">
                      <Button variant="outline" onClick={() => setShowSaveDocsDialog(true)} disabled={loading || batchData.length === 0}>
                          <FolderDown className="w-4 h-4 mr-2" /> Save to Docs
                      </Button>
                      <Button 
                        onClick={() => generateBatchPDF('download')} 
                        disabled={loading || batchData.length === 0}
                        variant={noticeType === 'final' ? "destructive" : "default"}
                      >
                          {loading ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <FileDown className="w-4 h-4 mr-2" />}
                          {noticeType === 'final' ? 'Generate FINAL Notices' : 'Generate Reminder Notices'}
                      </Button>
                  </div>
              </div>
          </CardHeader>
          <CardContent>
              {batchData.length === 0 ? (
                  <div className="text-center py-12 text-muted-foreground border-2 border-dashed rounded-lg">
                      <p>No records in batch. Use "Load from DB" to load owners with outstanding balances.</p>
                  </div>
              ) : (
                  <div className="rounded-md border">
                      <Table>
                          <TableHeader>
                              <TableRow>
                                  <TableHead>Owner Name</TableHead>
                                  <TableHead>Property Address</TableHead>
                                  <TableHead>Letters Generated</TableHead>
                                  <TableHead>Total Due</TableHead>
                                  <TableHead className="w-[100px]"></TableHead>
                              </TableRow>
                          </TableHeader>
                          <TableBody>
                              {batchData.map((item) => (
                                  <TableRow key={item.id}>
                                      <TableCell className="font-medium">{item.ownerName}</TableCell>
                                      <TableCell>{item.propertyAddress}</TableCell>
                                      <TableCell>
                                          <div className="flex flex-col gap-1">
                                             <Badge variant="outline" className="w-fit text-xs font-normal">Primary</Badge>
                                             {item.alternateAddresses && item.alternateAddresses.map((alt, idx) => (
                                                <Badge key={idx} variant="secondary" className="w-fit text-xs font-normal">+ Alternate {idx + 1}</Badge>
                                             ))}
                                          </div>
                                      </TableCell>
                                      <TableCell>${getTotal(item.items, item.hiddenItems)}</TableCell>
                                      <TableCell>
                                          <Button variant="ghost" size="icon" onClick={() => removeItem(item.id)}>
                                              <Trash2 className="w-4 h-4 text-destructive" />
                                          </Button>
                                      </TableCell>
                                  </TableRow>
                              ))}
                          </TableBody>
                      </Table>
                  </div>
              )}
          </CardContent>
      </Card>

      <SaveToDocumentsDialog
          open={showSaveDocsDialog}
          onOpenChange={setShowSaveDocsDialog}
          onSave={handleSaveToDocuments}
          defaultName={`Batch ${noticeType === 'final' ? 'Final' : 'Reminder'} Notices`}
          defaultClientId={selectedAssociationId}
      />

      {/* Account Selection Dialog */}
      <Dialog open={showSelectionDialog} onOpenChange={setShowSelectionDialog}>
        <DialogContent className="max-w-3xl max-h-[85vh]">
          <DialogHeader>
            <DialogTitle>Select Accounts for Batch</DialogTitle>
            <DialogDescription>
              {candidateItems.length} accounts with outstanding balances found. Select which to include.
            </DialogDescription>
          </DialogHeader>
          <div className="flex items-center justify-between px-1 py-2 border-b">
            <div className="flex items-center gap-2">
              <Checkbox
                checked={selectedCandidateIds.size === candidateItems.length && candidateItems.length > 0}
                onCheckedChange={toggleAllCandidates}
              />
              <span className="text-sm font-medium">Select All</span>
            </div>
            <Badge variant="secondary">
              {selectedCandidateIds.size} of {candidateItems.length} selected
            </Badge>
          </div>
          <ScrollArea className="h-[400px] pr-2">
            <div className="space-y-1">
              {candidateItems.map(item => (
                <div
                  key={item.id}
                  className={`flex items-center gap-3 p-3 rounded-md border cursor-pointer transition-colors ${
                    selectedCandidateIds.has(item.id) ? 'bg-primary/5 border-primary/30' : 'hover:bg-muted/50'
                  }`}
                  onClick={() => toggleCandidate(item.id)}
                >
                  <Checkbox
                    checked={selectedCandidateIds.has(item.id)}
                    onCheckedChange={() => toggleCandidate(item.id)}
                  />
                  <div className="flex-1 min-w-0">
                    <p className="font-medium text-sm truncate">{item.ownerName}</p>
                    <p className="text-xs text-muted-foreground truncate">{item.propertyAddress || 'No address'}</p>
                  </div>
                  <div className="text-right shrink-0">
                    <p className="font-semibold text-sm text-destructive">
                      ${item.totalDue.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                    </p>
                    <p className="text-xs text-muted-foreground">{item.accountNo || ''}</p>
                  </div>
                </div>
              ))}
            </div>
          </ScrollArea>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowSelectionDialog(false)}>Cancel</Button>
            <Button onClick={handleConfirmSelection}>
              Add {selectedCandidateIds.size} to Batch
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
