"use client";

/**
 * App chrome — dark navy sidebar with Lucide icons.
 * Nav groups: Pipeline / Activities / Insights / Admin (+ Dashboard top-level).
 * Items respect role + optional per-user module permissions.
 */

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useMemo, useState, type ComponentType } from "react";
import {
  LayoutDashboard,
  Users,
  UserPlus,
  Landmark,
  UserX,
  GitBranchPlus,
  ListTodo,
  BadgeCheck,
  ClipboardCheck,
  Contact,
  BarChart3,
  FileSpreadsheet,
  LineChart,
  Megaphone,
  PieChart,
  Shield,
  Database,
  Radio,
  Building2,
  type LucideProps,
} from "lucide-react";
import { useAuth } from "@/lib/auth";
import type { ApiUser } from "@/lib/api";

type IconType = ComponentType<LucideProps>;

type NavItem = {
  href: string;
  label: string;
  icon: IconType;
  roles?: string[];
  permission?: string;
  exact?: boolean;
};

type NavGroup = {
  title: string;
  items: NavItem[];
};

const DASHBOARD_ITEM: NavItem = {
  href: "/dashboard",
  label: "Dashboard",
  icon: LayoutDashboard,
  exact: true,
  permission: "dashboard.view",
};

/** Clearer IA: pipeline work, follow-ups, insights, then admin masters. */
const NAV: NavGroup[] = [
  {
    title: "Pipeline",
    items: [
      { href: "/leads", label: "All Leads", icon: Users, exact: true, permission: "leads.view" },
      { href: "/leads/new", label: "Add Lead", icon: UserPlus, permission: "leads.create" },
      { href: "/lead-bank", label: "Lead Bank", icon: Landmark, permission: "leads.bank" },
      { href: "/unattended", label: "Unattended", icon: UserX, permission: "leads.unattended" },
      { href: "/allocation", label: "Allocation", icon: GitBranchPlus, permission: "leads.allocation" },
    ],
  },
  {
    title: "Activities",
    items: [
      { href: "/tasks", label: "Tasks", icon: ListTodo, permission: "tasks.view" },
      {
        href: "/activity-approval",
        label: "Activity Approval",
        icon: BadgeCheck,
        roles: ["super-admin", "sales-head", "branch-head", "team-leader"],
        permission: "activity.approval",
      },
      { href: "/activity-review", label: "Activity Review", icon: ClipboardCheck, permission: "activity.review" },
      {
        href: "/lead-masters",
        label: "Lead Masters",
        icon: Contact,
        roles: ["super-admin", "sales-head", "branch-head"],
        permission: "lead_masters.view",
      },
    ],
  },
  {
    title: "Insights",
    items: [
      { href: "/reports", label: "Reports Hub", icon: BarChart3, exact: true, permission: "reports.view" },
      {
        href: "/lead-prospect-report",
        label: "Lead Prospect Report",
        icon: FileSpreadsheet,
        permission: "reports.prospect",
      },
      { href: "/analytics", label: "Lead Analytics", icon: LineChart, permission: "analytics.view" },
      { href: "/campaigns", label: "Campaigns", icon: Megaphone, exact: true, permission: "campaigns.view" },
      { href: "/campaigns/report", label: "Campaign Report", icon: PieChart, permission: "campaigns.view" },
    ],
  },
  {
    title: "Admin",
    items: [
      {
        href: "/users",
        label: "Users",
        icon: Shield,
        roles: ["super-admin", "sales-head", "branch-head"],
        permission: "users.view",
        exact: true,
      },
      {
        href: "/masters",
        label: "Masters",
        icon: Database,
        roles: ["super-admin", "sales-head", "branch-head"],
        permission: "masters.view",
      },
      {
        href: "/sources",
        label: "Sources",
        icon: Radio,
        roles: ["super-admin", "sales-head", "branch-head"],
        permission: "sources.view",
      },
      {
        href: "/projects",
        label: "Projects",
        icon: Building2,
        roles: ["super-admin", "sales-head", "branch-head"],
        permission: "projects.view",
      },
    ],
  },
];

function isActive(pathname: string, item: NavItem) {
  if (item.exact) return pathname === item.href;
  if (item.href === "/leads") return pathname === "/leads" || pathname.startsWith("/leads/");
  return pathname === item.href || pathname.startsWith(`${item.href}/`);
}

function canSee(user: ApiUser, item: NavItem): boolean {
  if (user.permissions_locked) {
    if (!item.permission) return true;
    return (user.permissions || []).includes(item.permission);
  }
  if (user.role === "super-admin") return true;
  if (item.roles && (!user.role || !item.roles.includes(user.role))) return false;
  return true;
}

export function AppShell({ children }: { children: React.ReactNode }) {
  const { user, loading, logout } = useAuth();
  const pathname = usePathname();
  const router = useRouter();
  const [open, setOpen] = useState<Record<string, boolean>>({
    Pipeline: true,
    Activities: true,
    Insights: true,
    Admin: true,
  });

  useEffect(() => {
    if (!loading && !user) router.replace("/login");
  }, [loading, user, router]);

  const dashboardVisible = useMemo(() => {
    if (!user) return false;
    return canSee(user, DASHBOARD_ITEM);
  }, [user]);

  const groups = useMemo(() => {
    if (!user) return [];
    return NAV.map((group) => ({
      ...group,
      items: group.items.filter((item) => canSee(user, item)),
    })).filter((g) => g.items.length > 0);
  }, [user]);

  if (loading || !user) {
    return (
      <div className="ps-loading-screen">
        <div>
          <div className="ps-loading-pulse" aria-hidden />
          <div style={{ textAlign: "center", fontWeight: 600 }}>Loading Projectify Sales…</div>
        </div>
      </div>
    );
  }

  const initials = user.name
    .split(" ")
    .map((p) => p[0])
    .join("")
    .slice(0, 2)
    .toUpperCase();

  return (
    <div className="ps-shell">
      <aside className="ps-sidebar rise">
        <div className="ps-brand">
          <div className="ps-brand-mark" aria-hidden>
            P
          </div>
          <div>
            <div className="ps-brand-name">Projectify</div>
            <div className="ps-brand-tag">Sales · Lead CRM</div>
          </div>
        </div>

        <nav style={{ display: "grid", gap: "0.95rem", flex: 1 }}>
          {dashboardVisible ? (
            <Link
              href={DASHBOARD_ITEM.href}
              className={`ps-nav-link${isActive(pathname, DASHBOARD_ITEM) ? " ps-nav-link-active" : ""}`}
            >
              <LayoutDashboard className="ps-nav-icon" aria-hidden strokeWidth={2} />
              Dashboard
            </Link>
          ) : null}

          {groups.map((group) => (
            <div key={group.title}>
              <button
                type="button"
                className="ps-nav-group-btn"
                onClick={() => setOpen((s) => ({ ...s, [group.title]: !s[group.title] }))}
              >
                <span>{group.title}</span>
                <span style={{ fontSize: "0.95rem", opacity: 0.7 }}>{open[group.title] ? "−" : "+"}</span>
              </button>
              {open[group.title] ? (
                <div style={{ display: "grid", gap: "0.12rem", marginTop: "0.25rem" }}>
                  {group.items.map((link) => {
                    const active = isActive(pathname, link);
                    const Icon = link.icon;
                    return (
                      <Link
                        key={link.href}
                        href={link.href}
                        className={`ps-nav-link${active ? " ps-nav-link-active" : ""}`}
                      >
                        <Icon className="ps-nav-icon" aria-hidden strokeWidth={2} />
                        {link.label}
                      </Link>
                    );
                  })}
                </div>
              ) : null}
            </div>
          ))}
        </nav>

        <div className="ps-user-card">
          <div style={{ display: "flex", gap: "0.65rem", alignItems: "center" }}>
            <div className="dash-avatar" style={{ width: 38, height: 38, fontSize: "0.85rem" }}>
              {initials}
            </div>
            <div style={{ minWidth: 0 }}>
              <div
                style={{
                  fontWeight: 700,
                  fontSize: "0.95rem",
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                  color: "#f8fafc",
                }}
              >
                {user.name}
              </div>
              <div style={{ fontSize: "0.8rem", color: "var(--sidebar-muted)" }}>{user.role_label || user.role}</div>
              {user.branch?.name ? (
                <div style={{ fontSize: "0.75rem", color: "var(--sidebar-muted)", marginTop: 1 }}>{user.branch.name}</div>
              ) : null}
            </div>
          </div>
          <button
            className="ps-btn ps-btn-ghost"
            style={{ marginTop: "0.75rem", width: "100%", padding: "0.55rem" }}
            onClick={() => logout()}
          >
            Sign out
          </button>
        </div>
      </aside>
      <main className="ps-main">{children}</main>
    </div>
  );
}
