import { useState, useEffect } from "react";
import { FileCheck, Download, Save, FolderOpen, Plus, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Checkbox } from "@/components/ui/checkbox";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";
import { generateEstoppelPdf } from "@/lib/estoppelPdfGenerator";
import acmLogo from "@/assets/acm-logo.png";
import { useSavedFormTemplates } from "@/hooks/useSavedFormTemplates";
import LoadTemplateDialog from "@/components/LoadTemplateDialog";
import SaveToDocumentsDialog from "@/components/documents/SaveToDocumentsDialog";

const YesNoField = ({ label, value, onChange, includeNA = false }) => (
  <div className="flex items-center justify-between py-2">
    <span className="text-sm text-foreground">{label}</span>
    <RadioGroup value={value} onValueChange={onChange} className="flex items-center gap-4">
      <div className="flex items-center gap-1.5">
        <RadioGroupItem value="yes" id={`${label}-yes`} />
        <Label htmlFor={`${label}-yes`} className="text-xs font-normal">Yes</Label>
      </div>
      <div className="flex items-center gap-1.5">
        <RadioGroupItem value="no" id={`${label}-no`} />
        <Label htmlFor={`${label}-no`} className="text-xs font-normal">No</Label>
      </div>
      {includeNA && (
        <div className="flex items-center gap-1.5">
          <RadioGroupItem value="na" id={`${label}-na`} />
          <Label htmlFor={`${label}-na`} className="text-xs font-normal">N/A</Label>
        </div>
      )}
    </RadioGroup>
  </div>
);

const CurrencyInput = ({ label, value, onChange }) => (
  <div className="space-y-1">
    <Label className="text-xs">{label}</Label>
    <div className="relative">
      <span className="absolute left-2.5 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">$</span>
      <Input type="number" step="0.01" value={value} onChange={(e) => onChange(e.target.value)} className="text-sm pl-6 text-right" placeholder="0.00" />
    </div>
  </div>
);

export default function EstoppelForm() {
  const [associations, setAssociations] = useState([]);
  const [selectedAssociationId, setSelectedAssociationId] = useState("");
  const [units, setUnits] = useState([]);
  const [owners, setOwners] = useState([]);
  const [isSavingDb, setIsSavingDb] = useState(false);
  const [showSaveDocsDialog, setShowSaveDocsDialog] = useState(false);
  const [showSaveResidentDialog, setShowSaveResidentDialog] = useState(false);

  // Section 1: Header & Recipient
  const [font, setFont] = useState("Helvetica");
  const [fontSize, setFontSize] = useState("9");
  const [logoFile, setLogoFile] = useState(null);
  const [date, setDate] = useState(new Date().toISOString().split("T")[0]);
  const [parcelId, setParcelId] = useState("");
  const [recipientName, setRecipientName] = useState("");
  const [recipientAddress, setRecipientAddress] = useState("");
  const [reReference, setReReference] = useState("");
  const [legalDescription, setLegalDescription] = useState("");
  const [buyerBank, setBuyerBank] = useState("");
  const [seller, setSeller] = useState("");
  const [mailLine1, setMailLine1] = useState("");
  const [mailLine2, setMailLine2] = useState("");
  const [mailLine3, setMailLine3] = useState("");
  const [mailLine4, setMailLine4] = useState("");
  const [attachLedger, setAttachLedger] = useState(true);
  const [attachW9, setAttachW9] = useState(true);
  const [attachCertApproval, setAttachCertApproval] = useState(false);
  const [validationProof, setValidationProof] = useState(false);

  // Section 2: Financial
  const [payableTo1, setPayableTo1] = useState("");
  const [balanceAtClose, setBalanceAtClose] = useState("");
  const [advAssessments, setAdvAssessments] = useState("");
  const [masterPayments, setMasterPayments] = useState([]);
  const [otherAmounts, setOtherAmounts] = useState([]);
  const [accountStartupFee, setAccountStartupFee] = useState("");
  const [delinquencyFee, setDelinquencyFee] = useState("");

  // Section 3: Questionnaire
  const [q1Collections, setQ1Collections] = useState("no");
  const [q2Rate, setQ2Rate] = useState("0.00");
  const [q3Frequency, setQ3Frequency] = useState("Monthly");
  const [q4Capital, setQ4Capital] = useState("no");
  const [q5Utilities, setQ5Utilities] = useState("");
  const [q6SpecialAssessments, setQ6SpecialAssessments] = useState("no");
  const [q7Multiple, setQ7Multiple] = useState("no");
  const [q7bAnotherEstoppel, setQ7bAnotherEstoppel] = useState("no");
  const [q8Litigation, setQ8Litigation] = useState("no");
  const [q9PaymentAddress, setQ9PaymentAddress] = useState("5445 MURRELL ROAD, #102-197, VIERA, FLORIDA 32955");
  const [q10UnpaidAssessments, setQ10UnpaidAssessments] = useState("");
  const [q10Interest, setQ10Interest] = useState("");
  const [q10LateFees, setQ10LateFees] = useState("");
  const [q10AdminFees, setQ10AdminFees] = useState("");
  const [q10LegalFees, setQ10LegalFees] = useState("");
  const [q11OtherCharges, setQ11OtherCharges] = useState([]);
  const [q13LateFeesIncluded, setQ13LateFeesIncluded] = useState("no");
  const [q14NextDue, setQ14NextDue] = useState("");
  const [q15Fee, setQ15Fee] = useState("250.00");
  const [q15aPaid, setQ15aPaid] = useState("no");
  const [q16Recreational, setQ16Recreational] = useState("no");
  const [q17Violations, setQ17Violations] = useState("no");
  const [q18CertApproval, setQ18CertApproval] = useState("no");
  const [q19Background, setQ19Background] = useState("no");
  const [q20Application, setQ20Application] = useState("na");
  const [q21LandLeases, setQ21LandLeases] = useState("no");
  const [q22Parking, setQ22Parking] = useState("no");
  const [q23FirstRefusal, setQ23FirstRefusal] = useState("no");
  const [q24Foreclosure, setQ24Foreclosure] = useState("no");
  const [q25BoardApproval, setQ25BoardApproval] = useState("no");
  const [q26Liens, setQ26Liens] = useState("no");
  const [q27Insurance, setQ27Insurance] = useState("Contact Agency");
  const [q28Flood, setQ28Flood] = useState("Contact Agency");
  const [masterAssocInfo, setMasterAssocInfo] = useState("");
  const [additionalInfo, setAdditionalInfo] = useState("");

  const templates = useSavedFormTemplates("estoppel");

  const getFormData = () => ({
    font, fontSize, date, parcelId, recipientName, recipientAddress, reReference, legalDescription,
    buyerBank, seller, mailLine1, mailLine2, mailLine3, mailLine4,
    attachLedger, attachW9, attachCertApproval, validationProof,
    payableTo1, balanceAtClose, advAssessments, masterPayments, otherAmounts,
    accountStartupFee, delinquencyFee,
    q1Collections, q2Rate, q3Frequency, q4Capital, q5Utilities, q6SpecialAssessments,
    q7Multiple, q7bAnotherEstoppel, q8Litigation, q9PaymentAddress,
    q10UnpaidAssessments, q10Interest, q10LateFees, q10AdminFees, q10LegalFees,
    q11OtherCharges, q13LateFeesIncluded, q14NextDue, q15Fee, q15aPaid,
    q16Recreational, q17Violations, q18CertApproval, q19Background, q20Application,
    q21LandLeases, q22Parking, q23FirstRefusal, q24Foreclosure, q25BoardApproval,
    q26Liens, q27Insurance, q28Flood, masterAssocInfo, additionalInfo,
  });
  const applyFormData = (d) => {
    const setters = {
      font: setFont, fontSize: setFontSize, date: setDate, parcelId: setParcelId,
      recipientName: setRecipientName, recipientAddress: setRecipientAddress,
      reReference: setReReference, legalDescription: setLegalDescription,
      buyerBank: setBuyerBank, seller: setSeller,
      mailLine1: setMailLine1, mailLine2: setMailLine2, mailLine3: setMailLine3, mailLine4: setMailLine4,
      attachLedger: setAttachLedger, attachW9: setAttachW9, attachCertApproval: setAttachCertApproval,
      validationProof: setValidationProof,
      payableTo1: setPayableTo1, balanceAtClose: setBalanceAtClose,
      advAssessments: setAdvAssessments, accountStartupFee: setAccountStartupFee,
      delinquencyFee: setDelinquencyFee,
      q1Collections: setQ1Collections, q2Rate: setQ2Rate, q3Frequency: setQ3Frequency,
      q4Capital: setQ4Capital, q5Utilities: setQ5Utilities, q6SpecialAssessments: setQ6SpecialAssessments,
      q7Multiple: setQ7Multiple, q7bAnotherEstoppel: setQ7bAnotherEstoppel,
      q8Litigation: setQ8Litigation, q9PaymentAddress: setQ9PaymentAddress,
      q10UnpaidAssessments: setQ10UnpaidAssessments, q10Interest: setQ10Interest,
      q10LateFees: setQ10LateFees, q10AdminFees: setQ10AdminFees, q10LegalFees: setQ10LegalFees,
      q13LateFeesIncluded: setQ13LateFeesIncluded, q14NextDue: setQ14NextDue,
      q15Fee: setQ15Fee, q15aPaid: setQ15aPaid,
      q16Recreational: setQ16Recreational, q17Violations: setQ17Violations,
      q18CertApproval: setQ18CertApproval, q19Background: setQ19Background,
      q20Application: setQ20Application, q21LandLeases: setQ21LandLeases,
      q22Parking: setQ22Parking, q23FirstRefusal: setQ23FirstRefusal,
      q24Foreclosure: setQ24Foreclosure, q25BoardApproval: setQ25BoardApproval,
      q26Liens: setQ26Liens, q27Insurance: setQ27Insurance, q28Flood: setQ28Flood,
      masterAssocInfo: setMasterAssocInfo, additionalInfo: setAdditionalInfo,
    };
    Object.entries(setters).forEach(([key, setter]) => { if (d[key] !== undefined) setter(d[key]); });
    if (d.masterPayments) setMasterPayments(d.masterPayments);
    if (d.otherAmounts) setOtherAmounts(d.otherAmounts);
    if (d.q11OtherCharges) setQ11OtherCharges(d.q11OtherCharges);
  };
  const handleSaveEstoppel = () => templates.saveTemplate(`Estoppel - ${recipientName || seller || "Draft"}`, getFormData());
  const handleLoadEstoppel = async (id) => { const r = await templates.loadTemplate(id); if (r?.form_data) applyFormData(r.form_data); };

  useEffect(() => {
    supabase.from("associations").select("id, name, address, city, state, zip, phone, email").eq("status", "active").then(({ data }) => {
      if (data) setAssociations(data);
    });
  }, []);

  // Load units for the selected association so we can match to a Unit ID for "Save to Resident File"
  useEffect(() => {
    if (!selectedAssociationId) { setUnits([]); return; }
    supabase.from("units")
      .select("id, unit_number, address")
      .eq("association_id", selectedAssociationId)
      .then(({ data }) => setUnits(data || []));
  }, [selectedAssociationId]);

  // Try to resolve the unit number from the property address ("RE:" reference)
  const matchedUnit = (() => {
    if (!reReference || units.length === 0) return "";
    const norm = (s) => (s || "").toLowerCase().replace(/[^a-z0-9]/g, "");
    const ref = norm(reReference);
    return units.find(u => ref && norm(u.address) && (ref.includes(norm(u.address)) || norm(u.address).includes(ref))) || null;
  })();
  const matchedUnitNumber = matchedUnit?.unit_number || "";

  const total1 = (parseFloat(balanceAtClose) || 0) + (parseFloat(advAssessments) || 0) +
    masterPayments.reduce((s, p) => s + (parseFloat(p.amount) || 0), 0) +
    otherAmounts.reduce((s, p) => s + (parseFloat(p.amount) || 0), 0);
  const total2 = (parseFloat(accountStartupFee) || 0) + (parseFloat(delinquencyFee) || 0);
  const q10Subtotal = [q10UnpaidAssessments, q10Interest, q10LateFees, q10AdminFees, q10LegalFees]
    .reduce((s, v) => s + (parseFloat(v) || 0), 0);
  const q11Subtotal = q11OtherCharges.reduce((s, c) => s + (parseFloat(c.amount) || 0), 0);
  const q12Payoff = q10Subtotal + q11Subtotal;
  const grandTotal = total1 + total2 + parseFloat(q15Fee || 0);

  const buildFormData = () => ({
    font, fontSize: parseInt(fontSize), date, parcelId, recipientName, recipientAddress,
    reReference, legalDescription, buyerBank, seller,
    mailLines: [mailLine1, mailLine2, mailLine3, mailLine4],
    attachments: { ledger: attachLedger, w9: attachW9, certApproval: attachCertApproval },
    validationProof,
    payableTo1, balanceAtClose: parseFloat(balanceAtClose) || 0,
    advAssessments: parseFloat(advAssessments) || 0,
    masterPayments, otherAmounts,
    accountStartupFee: parseFloat(accountStartupFee) || 0,
    delinquencyFee: parseFloat(delinquencyFee) || 0,
    total1, total2, grandTotal,
    questionnaire: {
      q1: q1Collections, q2: q2Rate, q3: q3Frequency, q4: q4Capital,
      q5: q5Utilities, q6: q6SpecialAssessments, q7: q7Multiple,
      q7b: q7bAnotherEstoppel, q8: q8Litigation, q9: q9PaymentAddress,
      q10: { unpaid: parseFloat(q10UnpaidAssessments)||0, interest: parseFloat(q10Interest)||0, late: parseFloat(q10LateFees)||0, admin: parseFloat(q10AdminFees)||0, legal: parseFloat(q10LegalFees)||0 },
      q11: q11OtherCharges, q11Subtotal, q12Payoff,
      q13: q13LateFeesIncluded, q14: q14NextDue,
      q15: parseFloat(q15Fee)||0, q15a: q15aPaid,
      q16: q16Recreational, q17: q17Violations, q18: q18CertApproval,
      q19: q19Background, q20: q20Application, q21: q21LandLeases,
      q22: q22Parking, q23: q23FirstRefusal, q24: q24Foreclosure,
      q25: q25BoardApproval, q26: q26Liens, q27: q27Insurance, q28: q28Flood,
    },
    masterAssocInfo, additionalInfo,
  });

  const handleGeneratePdf = async () => {
    try {
      await generateEstoppelPdf(buildFormData(), acmLogo);
      toast.success("Estoppel PDF generated successfully");
    } catch (err) {
      console.error(err);
      toast.error("Failed to generate PDF");
    }
  };

  const handleGeneratePdfBlob = async () => {
    return await generateEstoppelPdf(buildFormData(), acmLogo, true);
  };

  const handleSaveToDb = async () => {
    if (!selectedAssociationId) {
      toast.error("Please select an association first");
      return;
    }
    setIsSavingDb(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      const { error } = await supabase.from("estoppels").insert({
        association_id: selectedAssociationId,
        requestor_name: recipientName || null,
        requestor_email: null,
        address: reReference || null,
        fee: parseFloat(q15Fee) || null,
        status: "completed",
        requested_date: date || null,
        completed_date: new Date().toISOString(),
        created_by: user?.id || null,
        notes: JSON.stringify(getFormData()),
      });
      if (error) throw error;
      toast.success("Estoppel saved to database");
    } catch (err) {
      console.error(err);
      toast.error("Failed to save: " + (err.message || "Unknown error"));
    } finally {
      setIsSavingDb(false);
    }
  };

  return (
    <div className="flex flex-col gap-6 p-6 max-w-4xl">
      {/* Header */}
      <div className="flex items-center gap-3">
        <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
          <FileCheck className="h-5 w-5 text-primary" />
        </div>
        <div>
          <h2 className="text-lg font-semibold text-foreground">Estoppel Certificate</h2>
          <p className="text-sm text-muted-foreground">{templates.currentTemplateId ? `Editing: ${templates.currentTemplateName}` : "New Draft"}</p>
        </div>
        <div className="ml-auto flex gap-1.5">
          <Button variant="outline" size="sm" className="gap-1 text-xs h-8" onClick={() => { templates.newTemplate(); }}><Plus className="h-3 w-3" /> New</Button>
          <LoadTemplateDialog templates={templates.savedTemplates} onLoad={handleLoadEstoppel} onDelete={templates.deleteTemplate} />
          <Button variant="outline" size="sm" className="gap-1 text-xs h-8" onClick={handleSaveEstoppel}><Save className="h-3 w-3" /> Save</Button>
        </div>
      </div>

      {/* SECTION 1 */}
      <Card>
        <CardContent className="pt-6 space-y-5">
          <div>
            <h3 className="text-lg font-bold text-foreground">1. Header & Recipient Information</h3>
            <p className="text-sm text-muted-foreground">Information about the property, buyer, seller, and requester.</p>
          </div>

          <div className="space-y-1.5">
            <Label className="text-xs uppercase tracking-wider text-muted-foreground">Association</Label>
            <Select value={selectedAssociationId} onValueChange={setSelectedAssociationId}>
              <SelectTrigger className="text-sm"><SelectValue placeholder="Select Association" /></SelectTrigger>
              <SelectContent>
                {associations.map(a => <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>)}
              </SelectContent>
            </Select>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1.5">
              <Label className="text-xs uppercase tracking-wider text-muted-foreground">T Font</Label>
              <Select value={font} onValueChange={setFont}>
                <SelectTrigger className="text-sm"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="Helvetica">Helvetica</SelectItem>
                  <SelectItem value="Times">Times New Roman</SelectItem>
                  <SelectItem value="Courier">Courier</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs uppercase tracking-wider text-muted-foreground">Size (PT)</Label>
              <Input type="number" value={fontSize} onChange={e => setFontSize(e.target.value)} className="text-sm" />
            </div>
          </div>

          <div className="border rounded-lg p-4 space-y-1">
            <Label className="text-sm font-medium">Company Logo (Optional)</Label>
            <div className="flex items-center gap-3">
              <Input type="file" accept="image/*" onChange={e => setLogoFile(e.target.files?.[0] || null)} className="text-sm" />
              <span className="text-xs text-muted-foreground italic">Default Avria logo will be used if none uploaded.</span>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1.5">
              <Label className="text-xs">Date</Label>
              <Input type="date" value={date} onChange={e => setDate(e.target.value)} className="text-sm" />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs">Parcel ID</Label>
              <Input value={parcelId} onChange={e => setParcelId(e.target.value)} placeholder="e.g. 12-34-56-78" className="text-sm" />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1.5">
              <Label className="text-xs">Recipient Name (TO:)</Label>
              <Input value={recipientName} onChange={e => setRecipientName(e.target.value)} placeholder="Law Firm or Title Co." className="text-sm" />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs">Recipient Address</Label>
              <Textarea value={recipientAddress} onChange={e => setRecipientAddress(e.target.value)} placeholder="Address line 1&#10;Address line 2" className="text-sm min-h-[60px]" />
            </div>
          </div>

          <div className="space-y-1.5">
            <Label className="text-xs">RE: Reference (Unit/Property)</Label>
            <Textarea value={reReference} onChange={e => setReReference(e.target.value)} className="text-sm min-h-[50px]" />
          </div>

          <div className="space-y-1.5">
            <Label className="text-xs">Legal Description</Label>
            <Textarea value={legalDescription} onChange={e => setLegalDescription(e.target.value)} placeholder="Provide the full legal description of the property." className="text-sm min-h-[60px]" />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1.5">
              <Label className="text-xs">Buyer / Bank</Label>
              <Textarea value={buyerBank} onChange={e => setBuyerBank(e.target.value)} className="text-sm min-h-[50px]" />
            </div>
            <div className="space-y-1.5">
              <Label className="text-xs">Seller</Label>
              <Textarea value={seller} onChange={e => setSeller(e.target.value)} className="text-sm min-h-[50px]" />
            </div>
          </div>

          <div className="border rounded-lg p-4 space-y-3">
            <Label className="text-sm font-medium">Seller Mailing Address (Autofilled)</Label>
            <div className="grid grid-cols-2 gap-3">
              <Input value={mailLine1} onChange={e => setMailLine1(e.target.value)} placeholder="Mail Line 1" className="text-sm" />
              <Input value={mailLine2} onChange={e => setMailLine2(e.target.value)} placeholder="Mail Line 2" className="text-sm" />
              <Input value={mailLine3} onChange={e => setMailLine3(e.target.value)} placeholder="Mail Line 3" className="text-sm" />
              <Input value={mailLine4} onChange={e => setMailLine4(e.target.value)} placeholder="Mail Line 4" className="text-sm" />
            </div>
          </div>

          <div className="flex items-center gap-6">
            <span className="text-sm font-medium">Attachments:</span>
            <div className="flex items-center gap-2"><Checkbox checked={attachLedger} onCheckedChange={setAttachLedger} /><Label className="text-sm">Ledger</Label></div>
            <div className="flex items-center gap-2"><Checkbox checked={attachW9} onCheckedChange={setAttachW9} /><Label className="text-sm">W-9</Label></div>
            <div className="flex items-center gap-2"><Checkbox checked={attachCertApproval} onCheckedChange={setAttachCertApproval} /><Label className="text-sm">Cert. of Approval</Label></div>
          </div>

          <div className="border rounded-lg p-4 flex items-center justify-between">
            <div>
              <p className="text-sm font-medium">Validation of Proof</p>
              <p className="text-xs text-muted-foreground">When enabled, you can optionally generate a proof document detailing this estoppel.</p>
            </div>
            <Switch checked={validationProof} onCheckedChange={setValidationProof} />
          </div>
        </CardContent>
      </Card>

      {/* SECTION 2 */}
      <Card>
        <CardContent className="pt-6 space-y-5">
          <div>
            <h3 className="text-lg font-bold text-foreground">2. Financial Information</h3>
            <p className="text-sm text-muted-foreground">Closing amounts and fees.</p>
          </div>

          <div className="grid grid-cols-2 gap-6">
            <div className="space-y-4">
              <div className="space-y-1.5">
                <Label className="text-xs uppercase tracking-wider text-muted-foreground">Payable To #1</Label>
                <Textarea value={payableTo1} onChange={e => setPayableTo1(e.target.value)} placeholder="Payable To Name..." className="text-sm min-h-[60px]" />
              </div>
              <CurrencyInput label="Balance at Close [2]" value={balanceAtClose} onChange={setBalanceAtClose} />
              <CurrencyInput label="Adv. Assessments [3]" value={advAssessments} onChange={setAdvAssessments} />

              <div className="flex items-center justify-between">
                <span className="text-xs uppercase tracking-wider text-muted-foreground font-semibold">Association Master Payments</span>
                <Button variant="link" size="sm" className="text-xs h-auto p-0" onClick={() => setMasterPayments([...masterPayments, { desc: "", amount: "" }])}>+ Add</Button>
              </div>
              {masterPayments.map((p, i) => (
                <div key={i} className="flex gap-2">
                  <Input value={p.desc} onChange={e => { const c = [...masterPayments]; c[i].desc = e.target.value; setMasterPayments(c); }} placeholder="Description" className="text-sm flex-1" />
                  <Input type="number" step="0.01" value={p.amount} onChange={e => { const c = [...masterPayments]; c[i].amount = e.target.value; setMasterPayments(c); }} className="text-sm w-28 text-right" placeholder="0.00" />
                </div>
              ))}

              <div className="flex items-center justify-between">
                <span className="text-xs uppercase tracking-wider text-muted-foreground font-semibold">Other Amounts Due [4]</span>
                <Button variant="link" size="sm" className="text-xs h-auto p-0" onClick={() => setOtherAmounts([...otherAmounts, { desc: "", amount: "" }])}>+ Add</Button>
              </div>
              {otherAmounts.length === 0 && <p className="text-xs text-muted-foreground italic">No additional charges added</p>}
              {otherAmounts.map((p, i) => (
                <div key={i} className="flex gap-2">
                  <Input value={p.desc} onChange={e => { const c = [...otherAmounts]; c[i].desc = e.target.value; setOtherAmounts(c); }} placeholder="Description" className="text-sm flex-1" />
                  <Input type="number" step="0.01" value={p.amount} onChange={e => { const c = [...otherAmounts]; c[i].amount = e.target.value; setOtherAmounts(c); }} className="text-sm w-28 text-right" placeholder="0.00" />
                </div>
              ))}

              <Separator />
              <div className="flex items-center justify-between">
                <span className="text-sm font-bold">TOTAL #1</span>
                <span className="text-sm font-mono font-bold">${total1.toFixed(2)}</span>
              </div>
            </div>

            <div className="space-y-4">
              <div className="space-y-1.5">
                <Label className="text-xs uppercase tracking-wider text-muted-foreground">Payable To #2 (Avria)</Label>
                <p className="text-sm font-medium border-b pb-2">AVRIA COMMUNITY MANAGEMENT, LLC</p>
              </div>
              <CurrencyInput label="Account Start-up Fee" value={accountStartupFee} onChange={setAccountStartupFee} />
              <CurrencyInput label="Delinquency Fee" value={delinquencyFee} onChange={setDelinquencyFee} />
              <Separator />
              <div className="flex items-center justify-between">
                <span className="text-sm font-bold">TOTAL #2</span>
                <span className="text-sm font-mono font-bold">${total2.toFixed(2)}</span>
              </div>
            </div>
          </div>

          <div className="bg-muted/50 border rounded-lg p-4">
            <div className="flex items-center gap-2 mb-3">
              <span className="text-sm">📊</span>
              <h4 className="text-sm font-bold">Total Amounts Due Calculation</h4>
            </div>
            <div className="grid grid-cols-4 gap-3">
              <div className="text-center p-3 border rounded bg-background">
                <p className="text-xs text-muted-foreground">Total #1</p>
                <p className="text-sm font-mono font-bold">${total1.toFixed(2)}</p>
              </div>
              <div className="text-center p-3 border rounded bg-background">
                <p className="text-xs text-muted-foreground">Total #2</p>
                <p className="text-sm font-mono font-bold">${total2.toFixed(2)}</p>
              </div>
              <div className="text-center p-3 border rounded bg-background">
                <p className="text-xs text-muted-foreground">Payoff (Q12)</p>
                <p className="text-sm font-mono font-bold text-destructive">${q12Payoff.toFixed(2)}</p>
              </div>
              <div className="text-center p-3 border-2 border-destructive rounded bg-background">
                <p className="text-xs text-destructive font-semibold">GRAND TOTAL</p>
                <p className="text-lg font-mono font-bold text-destructive">${grandTotal.toFixed(2)}</p>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* SECTION 3: Questionnaire */}
      <Card>
        <CardContent className="pt-6 space-y-4">
          <div>
            <h3 className="text-lg font-bold text-foreground">3. Questionnaire</h3>
            <p className="text-sm text-muted-foreground">Detailed property and association status.</p>
          </div>

          <YesNoField label="1. Is property in collections?" value={q1Collections} onChange={setQ1Collections} />

          <div className="grid grid-cols-2 gap-4">
            <CurrencyInput label="2. Assessment Rate" value={q2Rate} onChange={setQ2Rate} />
            <div className="space-y-1.5">
              <Label className="text-xs">3. Assessment Frequency</Label>
              <Select value={q3Frequency} onValueChange={setQ3Frequency}>
                <SelectTrigger className="text-sm"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="Monthly">Monthly</SelectItem>
                  <SelectItem value="Quarterly">Quarterly</SelectItem>
                  <SelectItem value="Semi-Annually">Semi-Annually</SelectItem>
                  <SelectItem value="Annually">Annually</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <YesNoField label="4. Capital Contribution?" value={q4Capital} onChange={setQ4Capital} />

          <div className="space-y-1.5">
            <Label className="text-xs">5. Utilities Included</Label>
            <Input value={q5Utilities} onChange={e => setQ5Utilities(e.target.value)} placeholder="e.g. Water, Sewer, Trash" className="text-sm" />
          </div>

          <YesNoField label="6. Pending Special Assessments?" value={q6SpecialAssessments} onChange={setQ6SpecialAssessments} />
          <YesNoField label="7. Multiple Associations?" value={q7Multiple} onChange={setQ7Multiple} />
          <YesNoField label="Is another estoppel required?" value={q7bAnotherEstoppel} onChange={setQ7bAnotherEstoppel} />
          <YesNoField label="8. Ongoing Litigation?" value={q8Litigation} onChange={setQ8Litigation} />

          <div className="space-y-1.5">
            <Label className="text-xs">9. Payment Address</Label>
            <Input value={q9PaymentAddress} onChange={e => setQ9PaymentAddress(e.target.value)} className="text-sm" />
          </div>

          <Separator />
          <h4 className="text-sm font-bold">10. Breakdown of unpaid amounts</h4>
          <div className="grid grid-cols-2 gap-4">
            <CurrencyInput label="Unpaid Assessments" value={q10UnpaidAssessments} onChange={setQ10UnpaidAssessments} />
            <CurrencyInput label="Interest" value={q10Interest} onChange={setQ10Interest} />
            <CurrencyInput label="Late Fees" value={q10LateFees} onChange={setQ10LateFees} />
            <CurrencyInput label="Admin Fees" value={q10AdminFees} onChange={setQ10AdminFees} />
            <CurrencyInput label="Legal Fees" value={q10LegalFees} onChange={setQ10LegalFees} />
          </div>

          <Separator />
          <div className="flex items-center justify-between">
            <h4 className="text-sm font-bold">11. Other amounts due</h4>
            <Button variant="link" size="sm" className="text-xs h-auto p-0" onClick={() => setQ11OtherCharges([...q11OtherCharges, { desc: "", amount: "" }])}>+ Add Charge</Button>
          </div>
          {q11OtherCharges.length === 0 && <p className="text-xs text-muted-foreground italic">No additional charges added</p>}
          {q11OtherCharges.map((c, i) => (
            <div key={i} className="flex gap-2">
              <Input value={c.desc} onChange={e => { const u = [...q11OtherCharges]; u[i].desc = e.target.value; setQ11OtherCharges(u); }} placeholder="Description" className="text-sm flex-1" />
              <Input type="number" step="0.01" value={c.amount} onChange={e => { const u = [...q11OtherCharges]; u[i].amount = e.target.value; setQ11OtherCharges(u); }} className="text-sm w-28 text-right" placeholder="0.00" />
            </div>
          ))}
          <div className="flex items-center justify-between">
            <span className="text-sm">Subtotal (Q11)</span>
            <span className="text-sm font-mono font-bold">${q11Subtotal.toFixed(2)}</span>
          </div>

          <div className="bg-muted/50 border rounded-lg p-4">
            <h4 className="text-sm font-bold">12. Total Payoff Amount</h4>
            <div className="flex items-center justify-between mt-1">
              <span className="text-sm font-bold">Total Payoff (Q10 + Q11)</span>
              <span className="text-lg font-mono font-bold text-destructive">${q12Payoff.toFixed(2)}</span>
            </div>
          </div>

          <YesNoField label="13. Are late fees included in the payoff?" value={q13LateFeesIncluded} onChange={setQ13LateFeesIncluded} />

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1.5">
              <Label className="text-xs">14. Date next assessment is due</Label>
              <Input type="date" value={q14NextDue} onChange={e => setQ14NextDue(e.target.value)} className="text-sm" />
            </div>
            <CurrencyInput label="15. Estoppel Fee" value={q15Fee} onChange={setQ15Fee} />
          </div>

          <YesNoField label="15a. Has the estoppel fee been paid?" value={q15aPaid} onChange={setQ15aPaid} />
          <YesNoField label="16. Recreational lease/contract?" value={q16Recreational} onChange={setQ16Recreational} />
          <YesNoField label="17. Violations or code enforcement issues?" value={q17Violations} onChange={setQ17Violations} />
          <YesNoField label="18. Certificate of Approval required?" value={q18CertApproval} onChange={setQ18CertApproval} />
          <YesNoField label="19. Background check fee?" value={q19Background} onChange={setQ19Background} />
          <YesNoField label="20. Has application been made?" value={q20Application} onChange={setQ20Application} includeNA />
          <YesNoField label="21. Land leases?" value={q21LandLeases} onChange={setQ21LandLeases} />
          <YesNoField label="22. Parking restrictions?" value={q22Parking} onChange={setQ22Parking} />
          <YesNoField label="23. Right of first refusal?" value={q23FirstRefusal} onChange={setQ23FirstRefusal} />
          <YesNoField label="24. Foreclosure clause?" value={q24Foreclosure} onChange={setQ24Foreclosure} />
          <YesNoField label="25. Board approval required for transfer?" value={q25BoardApproval} onChange={setQ25BoardApproval} />
          <YesNoField label="26. Property subject to liens?" value={q26Liens} onChange={setQ26Liens} />

          <div className="space-y-1.5">
            <Label className="text-xs">27. Master Insurance Policy details</Label>
            <Input value={q27Insurance} onChange={e => setQ27Insurance(e.target.value)} className="text-sm" />
          </div>
          <div className="space-y-1.5">
            <Label className="text-xs">28. Flood Insurance Policy details</Label>
            <Input value={q28Flood} onChange={e => setQ28Flood(e.target.value)} className="text-sm" />
          </div>

          <Separator />
          <div className="space-y-1.5">
            <Label className="text-xs">Master Association Information</Label>
            <Textarea value={masterAssocInfo} onChange={e => setMasterAssocInfo(e.target.value)} placeholder="Additional master association details..." className="text-sm min-h-[60px]" />
          </div>
          <div className="space-y-1.5">
            <Label className="text-xs">Additional Information</Label>
            <Textarea value={additionalInfo} onChange={e => setAdditionalInfo(e.target.value)} placeholder="Any other relevant information..." className="text-sm min-h-[60px]" />
          </div>
        </CardContent>
      </Card>

      {/* Action Buttons */}
      <div className="flex items-center gap-2 justify-end sticky bottom-0 bg-background py-3 border-t">
        <Button variant="outline" size="sm" className="gap-1.5 text-xs" onClick={handleSaveToDb} disabled={isSavingDb}>
          {isSavingDb ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Save className="h-3.5 w-3.5" />} Save to DB
        </Button>
        <Button variant="outline" size="sm" className="gap-1.5 text-xs" onClick={() => setShowSaveDocsDialog(true)}>
          <FolderOpen className="h-3.5 w-3.5" /> Save to Docs
        </Button>
        {matchedUnitNumber && (
          <Button
            variant="outline"
            size="sm"
            className="gap-1.5 text-xs"
            onClick={() => setShowSaveResidentDialog(true)}
            title={`Save to Resident Files / ${matchedUnitNumber}`}
          >
            <FolderOpen className="h-3.5 w-3.5" /> Save to Resident File
          </Button>
        )}
        <Button size="sm" className="gap-1.5 text-xs" onClick={handleGeneratePdf}><Download className="h-3.5 w-3.5" /> Generate PDF</Button>
      </div>

      <SaveToDocumentsDialog
        open={showSaveDocsDialog}
        onOpenChange={setShowSaveDocsDialog}
        generatePdfBlob={handleGeneratePdfBlob}
        defaultTitle={`Estoppel Certificate - ${recipientName || seller || reReference || "Draft"}`}
        associationId={selectedAssociationId || null}
      />

      <SaveToDocumentsDialog
        open={showSaveResidentDialog}
        onOpenChange={setShowSaveResidentDialog}
        generatePdfBlob={handleGeneratePdfBlob}
        defaultTitle={`Estoppel Certificate - ${recipientName || seller || reReference || "Draft"}`}
        associationId={selectedAssociationId || null}
        residentFileMode
        unitId={matchedUnit?.id || ""}
        unitNumber={matchedUnitNumber}
      />
    </div>
  );
}
