"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { usePathname } from "next/navigation";
import type { User } from "@/types";

type NavItem = {
  href: string;
  label: string;
  description?: string;
};

type NavSection = {
  id: string;
  label: string;
  items: NavItem[];
};

const NAV_SECTIONS: NavSection[] = [
  {
    id: "cori-feature",
    label: "Ask CORI",
    items: [
      { href: "/dashboard", label: "CORI Briefing", description: "Daily business briefing and check-in" },
      { href: "/cori", label: "Ask CORI", description: "Focused dispatcher chat and guided assistance" },
      { href: "/cori/financial", label: "CORI Financial", description: "Plain money briefing by truck" },
      { href: "/cori/mail", label: "CORI Mail", description: "Email briefing and ready replies" },
      { href: "/cori/quotes", label: "CORI's Quotes", description: "Guided broker quote calls and call help" },
    ],
  },
  {
    id: "operations",
    label: "Operations",
    items: [
      { href: "/dispatch", label: "Dispatch Board", description: "Live loads and urgent work" },
      { href: "/loads", label: "Loads", description: "Find loads and open load records" },
      { href: "/routes", label: "Routes", description: "Plan load, truck, driver, weather, and stops" },
      { href: "/fleet-map", label: "Fleet Map", description: "Track dispatched trucks on the live/estimated map" },
      { href: "/documents", label: "Paperwork", description: "Missing proof, PODs, BOLs, and load documents" },
      { href: "/billing", label: "Billing Records", description: "Invoices, unpaid loads, and payment follow-up" },
    ],
  },
  {
    id: "people-assets",
    label: "People & Assets",
    items: [
      { href: "/drivers", label: "Drivers", description: "Driver records and status" },
      { href: "/trucks", label: "Trucks", description: "Fleet, equipment, and financial settings" },
      { href: "/owner-operators", label: "Owner Operators", description: "Independent capacity partners" },
    ],
  },
  {
    id: "crm",
    label: "CRM & Partners",
    items: [
      { href: "/crm", label: "CRM Overview", description: "Leads, partners, and follow-up" },
      { href: "/companies", label: "Companies", description: "General company relationship records" },
      { href: "/brokers", label: "Brokers", description: "Broker relationships and outreach" },
      { href: "/shippers", label: "Shippers", description: "Shipper accounts and activity" },
    ],
  },
];

function isRouteActive(pathname: string, href: string) {
  if (href === "/cori") return pathname === href;
  return pathname === href || pathname.startsWith(`${href}/`);
}

function matchSection(pathname: string, section: NavSection) {
  return section.items.some((item) => isRouteActive(pathname, item.href));
}

export function Sidebar({
  user,
  mobileOpen = false,
  onCloseMobile,
}: {
  user: User;
  mobileOpen?: boolean;
  onCloseMobile?: () => void;
}) {
  const pathname = usePathname();
  const workspaceSection = useMemo<NavSection>(() => {
    const items: NavItem[] = [
      { href: "/profile", label: "Profile & Security", description: "Account access and sign-in settings" },
    ];

    if (user?.role === "ORG_ADMIN") {
      items.push({ href: "/company", label: "Workspace Settings", description: "Company profile, team access, and notification settings" });
      items.push({ href: "/company/integrations", label: "Third-Party Integrations", description: "Email, maps, voice, accounting, payment, and API setup" });
    }

    return {
      id: "workspace",
      label: "Workspace",
      items,
    };
  }, [user]);

  const allSections = useMemo(() => [...NAV_SECTIONS, workspaceSection], [workspaceSection]);
  const [openSections, setOpenSections] = useState<Record<string, boolean>>(() => {
    const initialState: Record<string, boolean> = {};
    for (const section of [...NAV_SECTIONS, { id: "workspace" } as NavSection]) {
      initialState[section.id] = section.id === "cori-feature" || section.id === "operations";
    }
    return initialState;
  });

  useEffect(() => {
    if (typeof window === "undefined") return;
    const saved = window.localStorage.getItem("dispatchspot-sidebar-sections-v186");
    if (!saved) return;
    try {
      const parsed = JSON.parse(saved);
      setOpenSections((current) => ({ ...current, ...parsed }));
    } catch {
      // ignore invalid saved state
    }
  }, []);

  useEffect(() => {
    setOpenSections((current) => {
      const next = { ...current };
      let changed = false;
      for (const section of allSections) {
        if (matchSection(pathname, section) && !next[section.id]) {
          next[section.id] = true;
          changed = true;
        }
      }
      return changed ? next : current;
    });
  }, [allSections, pathname]);

  useEffect(() => {
    if (typeof window === "undefined") return;
    window.localStorage.setItem("dispatchspot-sidebar-sections-v186", JSON.stringify(openSections));
  }, [openSections]);

  function toggleSection(sectionId: string) {
    setOpenSections((current) => ({ ...current, [sectionId]: !current[sectionId] }));
  }

  const navContent = (
    <>
      <div className="border-b border-slate-200 px-5 py-5">
        <div className="flex items-center gap-3">
          <div className="flex h-10 w-10 items-center justify-center rounded-2xl bg-slate-900 text-sm font-semibold text-white">DS</div>
          <div className="min-w-0">
            <div className="truncate text-base font-semibold text-slate-900">Dispatch Spot</div>
            <div className="mt-0.5 text-xs text-slate-500">Clean CORI-first work surfaces</div>
          </div>
        </div>
      </div>

      <div className="border-b border-slate-200 px-5 py-4">
        <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400">Signed in workspace</div>
        <div className="mt-2 text-sm font-semibold text-slate-900">{user?.organization?.name || "Dispatch Spot Company"}</div>
        <div className="mt-1 text-xs text-slate-500">
          {user?.role === "ORG_ADMIN" ? "Company Admin" : user?.role === "DISPATCHER" ? "Dispatcher" : user?.role || "Connected user"}
        </div>
      </div>

      <nav className="space-y-2 p-3">
        {allSections.map((section) => {
          const sectionIsOpen = openSections[section.id] ?? false;
          const sectionIsActive = matchSection(pathname, section);

          return (
            <div key={section.id} className="rounded-2xl border border-slate-200 bg-white">
              <button
                type="button"
                onClick={() => toggleSection(section.id)}
                className={`flex w-full items-center justify-between rounded-2xl px-4 py-3 text-left transition ${
                  sectionIsActive ? "bg-slate-900 text-white" : "text-slate-800 hover:bg-slate-50"
                }`}
                aria-expanded={sectionIsOpen}
              >
                <div>
                  <div className="text-sm font-semibold">{section.label}</div>
                  <div className={`mt-0.5 text-[11px] ${sectionIsActive ? "text-slate-200" : "text-slate-500"}`}>
                    {section.items.length} {section.items.length === 1 ? "destination" : "destinations"}
                  </div>
                </div>
                <span className={`text-lg leading-none ${sectionIsActive ? "text-slate-200" : "text-slate-400"}`}>
                  {sectionIsOpen ? "−" : "+"}
                </span>
              </button>

              {sectionIsOpen ? (
                <ul className="space-y-1 px-2 pb-2">
                  {section.items.map((item) => {
                    const active = isRouteActive(pathname, item.href);
                    const isCoriFeature = section.id === "cori-feature";
                    return (
                      <li key={item.href}>
                        <Link
                          href={item.href}
                          onClick={onCloseMobile}
                          className={`block rounded-xl px-3 py-3 transition ${
                            active
                              ? "bg-slate-50 text-slate-950"
                              : isCoriFeature
                                ? "text-sky-700 hover:bg-sky-50"
                                : "border border-transparent text-slate-700 hover:border-slate-200 hover:bg-slate-50"
                          }`}
                        >
                          <div className={`text-sm font-medium ${isCoriFeature && !active ? "text-sky-700" : ""}`}>{item.label}</div>
                          {item.description ? <div className={`mt-1 text-[11px] ${isCoriFeature && !active ? "text-sky-600" : "text-slate-500"}`}>{item.description}</div> : null}
                        </Link>
                      </li>
                    );
                  })}
                </ul>
              ) : null}
            </div>
          );
        })}
      </nav>
    </>
  );

  return (
    <>
      <aside className="hidden h-screen w-80 shrink-0 overflow-y-auto border-r border-slate-200 bg-slate-50 xl:block">
        {navContent}
      </aside>

      {mobileOpen ? (
        <div className="fixed inset-0 z-50 xl:hidden">
          <button type="button" aria-label="Close navigation" onClick={onCloseMobile} className="absolute inset-0 bg-slate-950/40" />
          <aside className="relative h-full w-80 max-w-[88vw] overflow-y-auto border-r border-slate-200 bg-slate-50 shadow-2xl">
            <div className="flex items-center justify-between border-b border-slate-200 px-4 py-3">
              <div>
                <div className="text-sm font-semibold text-slate-900">Navigation</div>
                <div className="text-xs text-slate-500">Open a workspace area</div>
              </div>
              <button type="button" onClick={onCloseMobile} className="rounded-xl border border-slate-200 bg-white px-3 py-1.5 text-sm text-slate-700">
                Close
              </button>
            </div>
            {navContent}
          </aside>
        </div>
      ) : null}
    </>
  );
}
