import { useEffect, useState } from "react";
import { NavLink, Outlet, useLocation } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { useAssociationAccountingSystem } from "@/hooks/useAssociationAccountingSystem";
import { useAccountingCompany } from "@/hooks/useAccountingCompany";
import { Card, CardContent } from "@/components/ui/card";
import { Loader2 } from "lucide-react";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";

const LS_KEY = "selectedAssociation";

type NavItem = { to: string; label: string; end?: boolean };
type NavSection = { heading?: string; items: NavItem[] };

const NAV: NavSection[] = [
  { items: [{ to: "", label: "Dashboard", end: true }] },
  {
    heading: "HOA",
    items: [
      { to: "customers", label: "Homeowners" },
      { to: "assessments", label: "Assessments" },
      { to: "work-orders", label: "Work Orders" },
    ],
  },
  {
    heading: "Receivables",
    items: [
      { to: "receive-payments", label: "Receive Payments" },
      { to: "invoices", label: "Invoices" },
      { to: "estimates", label: "Estimates" },
    ],
  },
  {
    heading: "Payables",
    items: [
      { to: "bills", label: "Bills" },
      { to: "vendors", label: "Vendors" },
      { to: "expenses", label: "Expenses" },
    ],
  },
  {
    heading: "Accounting",
    items: [
      { to: "chart-of-accounts", label: "Chart of Accounts" },
      { to: "budgets", label: "Budgeting" },
      { to: "journal-entries", label: "Journal Entries" },
      { to: "banking", label: "Banking" },
      { to: "reconciliation", label: "Reconciliation" },
      { to: "deposits", label: "Make Deposit" },
      { to: "opening-balances", label: "Opening Balances" },
      { to: "reports", label: "Reports" },
    ],
  },
  {
    heading: "Setup",
    items: [{ to: "settings", label: "Settings" }],
  },
];

export default function AccountingLayout() {
  const { pathname } = useLocation();
  const [associations, setAssociations] = useState<{ id: string; name: string }[]>([]);
  const [associationId, setAssociationId] = useState<string | null>(() => {
    try { return JSON.parse(localStorage.getItem(LS_KEY) || "null")?.id ?? null; } catch { return null; }
  });

  useEffect(() => {
    supabase.from("associations").select("id, name").eq("status", "active").order("name")
      .then(({ data }) => {
        const list = data ?? [];
        setAssociations(list);
        if (list.length && !list.find((a) => a.id === associationId)) {
          setAssociationId(list[0].id);
          localStorage.setItem(LS_KEY, JSON.stringify(list[0]));
        }
      });
  }, []);

  const selectAssociation = (id: string) => {
    const next = associations.find((a) => a.id === id);
    if (!next) return;
    setAssociationId(id);
    localStorage.setItem(LS_KEY, JSON.stringify(next));
  };

  const { system, loading } = useAssociationAccountingSystem(associationId);
  const { companyId, loading: companyLoading, error: companyError } = useAccountingCompany(associationId);

  const renderBody = () => {
    if (loading) {
      return <div className="flex justify-center py-12"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>;
    }
    if (!associationId) {
      return (
        <Card>
          <CardContent className="py-10 text-center text-sm text-muted-foreground">
            Select an association from the dropdown above to begin.
          </CardContent>
        </Card>
      );
    }
    if (system !== "platform") {
      return (
        <Card>
          <CardContent className="py-10 text-center space-y-2">
            <h2 className="text-lg font-semibold">Platform Accounting is not enabled for this association</h2>
            <p className="text-sm text-muted-foreground">
              This association is currently set to <strong>{system === "zoho" ? "Zoho Books" : "Buildium"}</strong>.
              Switch the Accounting System to <strong>Platform</strong> in the association settings to use these tools.
            </p>
          </CardContent>
        </Card>
      );
    }
    if (companyLoading) {
      return <div className="flex justify-center py-12"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>;
    }
    if (companyError || !companyId) {
      return (
        <Card>
          <CardContent className="py-10 text-center space-y-2">
            <h2 className="text-lg font-semibold">Accounting setup is not ready</h2>
            <p className="text-sm text-muted-foreground">
              The accounting database objects are missing for this environment, so these pages cannot load yet.
            </p>
            {companyError ? <p className="text-xs text-muted-foreground">{companyError}</p> : null}
          </CardContent>
        </Card>
      );
    }
    return <Outlet />;
  };

  return (
    <div className="flex h-full min-h-[calc(100vh-4rem)] w-full">
      <aside className="w-64 shrink-0 border-r bg-card flex flex-col">
        <div className="px-4 py-4 border-b">
          <h1 className="text-lg font-bold tracking-tight">Accounting</h1>
          <p className="text-xs text-muted-foreground mt-0.5">Platform bookkeeping</p>
          <div className="mt-3">
            <label className="text-xs font-medium text-muted-foreground mb-1 block">Association</label>
            <Select
              value={associationId ?? ""}
              onValueChange={selectAssociation}
            >
              <SelectTrigger className="h-9">
                <SelectValue placeholder="Select association" />
              </SelectTrigger>
              <SelectContent>
                {associations.map((a) => (
                  <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>
        <nav className="flex-1 overflow-y-auto p-2 space-y-3">
          {NAV.map((section, sIdx) => (
            <div key={section.heading ?? `sec-${sIdx}`} className="space-y-0.5">
              {section.heading ? (
                <div className="px-3 pt-2 pb-1 text-[10px] font-semibold tracking-wider uppercase text-muted-foreground/70">
                  {section.heading}
                </div>
              ) : null}
              {section.items.map((n) => {
                const target = n.to ? `/dashboard/accounting/${n.to}` : "/dashboard/accounting";
                const isActive = n.end ? pathname === target : pathname.startsWith(target);
                return (
                  <NavLink
                    key={n.to || "dashboard"}
                    to={target}
                    end={n.end}
                    className={`block px-3 py-2 text-sm rounded-md transition-colors ${
                      isActive ? "bg-primary/10 text-primary font-medium" : "text-muted-foreground hover:bg-muted hover:text-foreground"
                    }`}
                  >
                    {n.label}
                  </NavLink>
                );
              })}
            </div>
          ))}
        </nav>
      </aside>
      <div className="flex-1 p-6 overflow-auto">{renderBody()}</div>
    </div>
  );
}