import { useState, useEffect, useMemo } from "react";
import { Receipt, Download, Plus, Trash2, Search, Users, FileText } from "lucide-react";
import { groupOwnersByUnit, combineOwnerNames, collectAllAddresses } from "@/lib/ownerAddressUtils";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ScrollArea } from "@/components/ui/scroll-area";
import { supabase } from "@/integrations/supabase/client";
import { generateHomeownerInvoicePdf } from "@/lib/generateHomeownerInvoicePdf";
import { useToast } from "@/components/ui/use-toast";
import { format } from "date-fns";

export default function InvoiceForm() {
  const { toast } = useToast();

  // Mode
  const [bulkMode, setBulkMode] = useState(false);

  // Association & owners
  const [associations, setAssociations] = useState([]);
  const [selectedAssocId, setSelectedAssocId] = useState("");
  const [owners, setOwners] = useState([]);
  const [selectedOwnerIds, setSelectedOwnerIds] = useState([]);
  const [ownerSearch, setOwnerSearch] = useState("");

  // Chart of accounts
  const [accounts, setAccounts] = useState([]);

  // Invoice fields
  const [invoiceDate, setInvoiceDate] = useState(new Date().toISOString().split("T")[0]);
  const [dueDate, setDueDate] = useState("");
  const [billingPeriod, setBillingPeriod] = useState("");
  const [invoiceNumber, setInvoiceNumber] = useState("");
  const [notes, setNotes] = useState("Thank you for your prompt payment.");
  const [lineItems, setLineItems] = useState([
    { id: 1, description: "Assessment Fee", accountId: "", amount: 0 },
  ]);

  // Company settings for PDF header
  const [companySettings, setCompanySettings] = useState({});
  const [useCompanyAsSender, setUseCompanyAsSender] = useState(false);

  // Load associations on mount
  useEffect(() => {
    supabase.from("associations").select("id, name, address, city, state, zip, phone, email, logo_url, care_of_address, mailing_address, zoho_organization_id").eq("status", "active").order("name")
      .then(({ data }) => setAssociations(data || []));

    // Load company settings
    supabase.from("company_settings").select("key, value")
      .then(({ data }) => {
        const settings = {};
        (data || []).forEach(s => { settings[s.key] = s.value; });
        setCompanySettings(settings);
      });
  }, []);

  // Load owners & COA when association changes
  useEffect(() => {
    if (!selectedAssocId) {
      setOwners([]);
      setAccounts([]);
      setSelectedOwnerIds([]);
      return;
    }

    supabase.from("owners").select("id, first_name, last_name, property_address, street_address, mailing_address, alternate_address_1, alternate_address_2, email, unit_id, units(account_number)").eq("status", "active")
      .eq("association_id", selectedAssocId)
      .order("last_name")
      .then(({ data }) => setOwners(data || []));

    // Filter the COA to the association's accounting system (zoho vs buildium).
    const assoc = associations.find(a => a.id === selectedAssocId);
    const system = assoc?.zoho_organization_id ? "zoho" : "buildium";
    supabase.from("chart_of_accounts").select("id, account_number, account_name, account_type")
      .eq("accounting_system", system)
      .eq("is_active", true)
      .order("account_number")
      .then(({ data }) => setAccounts(data || []));

    setSelectedOwnerIds([]);
  }, [selectedAssocId, associations]);

  // Auto-generate next invoice number
  useEffect(() => {
    if (!selectedAssocId) return;
    supabase.from("client_invoices")
      .select("invoice_number")
      .order("created_at", { ascending: false })
      .limit(1)
      .then(({ data }) => {
        if (data?.[0]?.invoice_number) {
          const match = data[0].invoice_number.match(/(\d+)$/);
          if (match) {
            const next = parseInt(match[1]) + 1;
            setInvoiceNumber(`INV-${String(next).padStart(4, "0")}`);
            return;
          }
        }
        setInvoiceNumber("INV-1001");
      });
  }, [selectedAssocId]);

  // Filter owners by search
  const filteredOwners = useMemo(() => {
    if (!ownerSearch) return owners;
    const q = ownerSearch.toLowerCase();
    return owners.filter(o =>
      `${o.first_name} ${o.last_name}`.toLowerCase().includes(q) ||
      (o.property_address || "").toLowerCase().includes(q) ||
      (o.account_number || "").toLowerCase().includes(q)
    );
  }, [owners, ownerSearch]);

  // Toggle owner selection
  const toggleOwner = (id) => {
    setSelectedOwnerIds(prev =>
      prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
    );
  };

  const selectAll = () => {
    if (selectedOwnerIds.length === filteredOwners.length) {
      setSelectedOwnerIds([]);
    } else {
      setSelectedOwnerIds(filteredOwners.map(o => o.id));
    }
  };

  // Line item helpers
  const addLine = () => {
    setLineItems([...lineItems, { id: Date.now(), description: "", accountId: "", amount: 0 }]);
  };

  const updateLine = (id, field, value) => {
    setLineItems(lineItems.map(li => li.id === id ? { ...li, [field]: value } : li));
  };

  const removeLine = (id) => {
    if (lineItems.length > 1) setLineItems(lineItems.filter(li => li.id !== id));
  };

  const total = lineItems.reduce((sum, li) => sum + (Number(li.amount) || 0), 0);

  // Selected owner for single mode
  const selectedOwner = !bulkMode && selectedOwnerIds.length === 1
    ? owners.find(o => o.id === selectedOwnerIds[0])
    : null;

  const selectedAssoc = associations.find(a => a.id === selectedAssocId);

  // Generate invoices
  const handleGenerate = async () => {
    const targetOwnerIds = bulkMode ? selectedOwnerIds : (selectedOwnerIds.length ? selectedOwnerIds : []);

    if (!selectedAssocId) {
      toast({ variant: "destructive", title: "Select an association" });
      return;
    }
    if (targetOwnerIds.length === 0) {
      toast({ variant: "destructive", title: "Select at least one homeowner" });
      return;
    }
    if (!lineItems.some(li => li.description && li.amount > 0)) {
      toast({ variant: "destructive", title: "Add at least one line item with an amount" });
      return;
    }

    const assoc = associations.find(a => a.id === selectedAssocId);
    const user = (await supabase.auth.getUser()).data.user;

    let invoiceCounter = 0;
    const baseMatch = invoiceNumber.match(/(\d+)$/);
    const baseNum = baseMatch ? parseInt(baseMatch[1]) : 1001;

    // Group selected owners by unit to combine co-owner names
    const selectedOwners = owners.filter(o => targetOwnerIds.includes(o.id));
    const unitGroups = groupOwnersByUnit(selectedOwners);
    let pdfCount = 0;

    for (const [, groupOwners] of unitGroups) {
      const combinedName = combineOwnerNames(groupOwners);
      const allAddresses = collectAllAddresses(groupOwners);
      const primaryOwner = groupOwners[0];

      const currentInvNum = bulkMode || unitGroups.size > 1
        ? `INV-${String(baseNum + invoiceCounter).padStart(4, "0")}`
        : (invoiceNumber || `INV-${String(baseNum).padStart(4, "0")}`);
      invoiceCounter++;

      // Save to client_invoices (one per unit group)
      const { data: invData, error: invError } = await supabase.from("client_invoices").insert({
        invoice_number: currentInvNum,
        association_id: selectedAssocId,
        amount: total,
        credits: 0,
        total: total,
        status: "sent",
        issue_date: invoiceDate || new Date().toISOString().split("T")[0],
        due_date: dueDate || null,
        source: "forms_letters",
        notes: notes || null,
        created_by: user?.id,
      }).select().single();

      if (!invError && invData) {
        await supabase.from("client_invoice_items").insert(
          lineItems.filter(li => li.description).map(li => ({
            invoice_id: invData.id,
            description: li.description,
            quantity: 1,
            unit_price: Number(li.amount || 0),
            amount: Number(li.amount || 0),
            is_credit: false,
          }))
        );
      }

      // Generate a PDF for EACH address (mailing + alternates)
      for (const addrCopy of allAddresses) {
        await generateHomeownerInvoicePdf({
          invoiceNumber: currentInvNum,
          invoiceDate: invoiceDate ? format(new Date(invoiceDate), "yyyy-MM-dd") : "",
          dueDate: dueDate ? format(new Date(dueDate), "yyyy-MM-dd") : "",
          billingPeriod,
          associationName: assoc?.name || "",
          associationCareOf: assoc?.care_of_address || "",
          associationMailingAddress: assoc?.mailing_address || "",
          companyName: companySettings.company_name || "Avria Community Management",
          companyAddress: companySettings.company_address || "",
          useCompanyAsSender,
          ownerName: combinedName,
          ownerAddress: primaryOwner.property_address || primaryOwner.street_address || "",
          ownerMailingAddress: addrCopy.address,
          ownerCity: "",
          ownerState: "",
          ownerZip: "",
          accountNumber: primaryOwner.units?.account_number || "",
          items: lineItems.filter(li => li.description).map(li => ({
            description: li.description,
            amount: Number(li.amount || 0),
          })),
          notes,
          logoUrl: assoc?.logo_url || null,
        });
        pdfCount++;
      }
    }

    toast({
      title: `${pdfCount} invoice PDF${pdfCount > 1 ? "s" : ""} generated & saved`,
    });
  };

  return (
    <div className="flex gap-6 p-6 max-w-5xl">
      {/* Main form area */}
      <div className="flex-1 space-y-5">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-lg font-semibold text-foreground">Invoice Editor</h2>
            <p className="text-[13px] text-muted-foreground">Create invoices for homeowners.</p>
          </div>
          <div className="flex items-center gap-2">
            <Label className="text-[12px] text-muted-foreground">Bulk Mode</Label>
            <Switch checked={bulkMode} onCheckedChange={setBulkMode} />
          </div>
        </div>

        <Separator />

        {/* Association select */}
        <div className="space-y-1.5">
          <Label className="text-[13px]">Association</Label>
          <Select value={selectedAssocId} onValueChange={setSelectedAssocId}>
            <SelectTrigger className={`text-[13px] ${selectedAssocId ? "border-primary" : ""}`}>
              <SelectValue placeholder="Select Association" />
            </SelectTrigger>
            <SelectContent>
              {associations.map(a => (
                <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
              ))}
            </SelectContent>
          </Select>
          <div className="flex items-center gap-2 mt-2">
            <Switch checked={useCompanyAsSender} onCheckedChange={setUseCompanyAsSender} />
            <Label className="text-[12px] text-muted-foreground">Send from company address instead of association</Label>
          </div>
        </div>

        {/* Owner selection */}
        {selectedAssocId && (
          <div className="space-y-2">
            {bulkMode ? (
              /* Bulk: multi-select with checkboxes */
              <div className="border rounded-lg">
                <div className="flex items-center justify-between px-3 py-2 border-b bg-muted/30">
                  <span className="text-[13px] font-medium">
                    Select Homeowners ({selectedOwnerIds.length})
                  </span>
                  <button
                    onClick={selectAll}
                    className="text-[12px] font-medium text-primary hover:underline"
                  >
                    {selectedOwnerIds.length === filteredOwners.length ? "Deselect All" : "Select All"}
                  </button>
                </div>
                <div className="px-3 py-2 border-b">
                  <div className="relative">
                    <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
                    <Input
                      placeholder="Filter owners..."
                      value={ownerSearch}
                      onChange={(e) => setOwnerSearch(e.target.value)}
                      className="pl-8 h-8 text-[13px]"
                    />
                  </div>
                </div>
                <ScrollArea className="max-h-[200px]">
                  <div className="divide-y">
                    {filteredOwners.map(o => (
                      <label
                        key={o.id}
                        className="flex items-center gap-3 px-3 py-2 cursor-pointer hover:bg-muted/30 transition-colors"
                      >
                        <Checkbox
                          checked={selectedOwnerIds.includes(o.id)}
                          onCheckedChange={() => toggleOwner(o.id)}
                        />
                        <span className="text-[13px] font-medium text-foreground">
                          {o.first_name} {o.last_name}
                        </span>
                        <span className="text-[11px] text-muted-foreground">
                          {o.property_address || o.street_address || ""}
                        </span>
                      </label>
                    ))}
                    {filteredOwners.length === 0 && (
                      <div className="text-center py-4 text-[13px] text-muted-foreground">
                        No owners found.
                      </div>
                    )}
                  </div>
                </ScrollArea>
              </div>
            ) : (
              /* Single: dropdown */
              <div className="space-y-1.5">
                <Label className="text-[13px]">Homeowner</Label>
                <Select
                  value={selectedOwnerIds[0] || ""}
                  onValueChange={(v) => setSelectedOwnerIds(v ? [v] : [])}
                >
                  <SelectTrigger className="text-[13px]">
                    <SelectValue placeholder="Select Owner" />
                  </SelectTrigger>
                  <SelectContent>
                    {owners.map(o => (
                      <SelectItem key={o.id} value={o.id}>
                        {o.first_name} {o.last_name}
                        {o.property_address ? ` — ${o.property_address}` : ""}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            )}
          </div>
        )}

        {/* Invoice details row */}
        <div className="grid grid-cols-4 gap-3">
          <div className="space-y-1.5">
            <Label className="text-[12px]">Invoice Date</Label>
            <Input type="date" value={invoiceDate} onChange={(e) => setInvoiceDate(e.target.value)} className="text-[13px]" />
          </div>
          <div className="space-y-1.5">
            <Label className="text-[12px]">Due Date</Label>
            <Input type="date" value={dueDate} onChange={(e) => setDueDate(e.target.value)} className="text-[13px]" />
          </div>
          <div className="space-y-1.5">
            <Label className="text-[12px]">Billing Period</Label>
            <Input placeholder="e.g. Jan 2024" value={billingPeriod} onChange={(e) => setBillingPeriod(e.target.value)} className="text-[13px]" />
          </div>
          <div className="space-y-1.5">
            <Label className="text-[12px]">Invoice #</Label>
            <Input
              placeholder={bulkMode ? "Auto-generated" : "Leave empty to auto-ge"}
              value={bulkMode ? "" : invoiceNumber}
              onChange={(e) => !bulkMode && setInvoiceNumber(e.target.value)}
              disabled={bulkMode}
              className="text-[13px]"
            />
          </div>
        </div>

        {/* Line Items */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <span className="text-[13px] font-semibold text-foreground">Line Items</span>
            <Button variant="outline" size="sm" className="gap-1.5 text-[12px] h-7" onClick={addLine}>
              <Plus className="h-3 w-3" /> Add Item
            </Button>
          </div>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="text-[12px]">Description</TableHead>
                <TableHead className="text-[12px]">Account</TableHead>
                <TableHead className="text-[12px] w-[120px]">Amount ($)</TableHead>
                <TableHead className="w-8" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {lineItems.map((li) => (
                <TableRow key={li.id}>
                  <TableCell>
                    <Input
                      value={li.description}
                      onChange={(e) => updateLine(li.id, "description", e.target.value)}
                      className="text-[13px] h-8"
                      placeholder="Item description"
                    />
                  </TableCell>
                  <TableCell>
                    <Select value={li.accountId} onValueChange={(v) => updateLine(li.id, "accountId", v)}>
                      <SelectTrigger className="text-[12px] h-8">
                        <SelectValue placeholder="Account..." />
                      </SelectTrigger>
                      <SelectContent>
                        {accounts.map(a => (
                          <SelectItem key={a.id} value={a.id}>
                            <span className="font-mono text-[11px] mr-1">{a.account_number}</span>
                            {a.account_name}
                            <span className="text-[10px] ml-1 text-muted-foreground uppercase">{a.account_type}</span>
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </TableCell>
                  <TableCell>
                    <Input
                      type="number"
                      step="0.01"
                      value={li.amount || ""}
                      onChange={(e) => updateLine(li.id, "amount", Number(e.target.value))}
                      className="text-[13px] h-8"
                    />
                  </TableCell>
                  <TableCell>
                    <button onClick={() => removeLine(li.id)} className="text-destructive/50 hover:text-destructive">
                      <Trash2 className="h-3.5 w-3.5" />
                    </button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
          <div className="flex justify-end pt-2 mt-2">
            <span className="text-[14px] font-bold">Total: ${total.toFixed(2)}</span>
          </div>
        </div>

        {/* Custom Message */}
        <div className="space-y-1.5">
          <Label className="text-[13px] font-medium">Custom Message / Notes</Label>
          <Textarea
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            placeholder="Thank you for your prompt payment."
            className="text-[13px] min-h-[60px]"
          />
        </div>
      </div>

      {/* Right sidebar: Actions */}
      <div className="w-[220px] shrink-0 space-y-4">
        <h3 className="text-[14px] font-semibold text-foreground">Actions</h3>
        <Button
          className="w-full gap-2"
          onClick={handleGenerate}
        >
          <FileText className="h-4 w-4" />
          Generate {bulkMode && selectedOwnerIds.length > 0 ? `${selectedOwnerIds.length} ` : ""}Invoice{bulkMode && selectedOwnerIds.length !== 1 ? "s" : ""}
        </Button>

        <div className="text-[12px] text-muted-foreground space-y-1.5 pt-2">
          <p className="font-medium text-foreground text-[13px]">Invoice Features:</p>
          <p>• System-generated sequential numbers</p>
          <p>• Auto-saved to history</p>
          <p>• Chart of Accounts mapped</p>
          <p>• Remittance slip included</p>
          <p>• <strong>Bulk Generation</strong> support</p>
        </div>
      </div>
    </div>
  );
}
