"use client";

import { useEffect, useMemo, useState, type CSSProperties, type ReactNode } from "react";
import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import {
  ChevronDownIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
  LogOutIcon,
  MenuIcon,
  UserIcon,
} from "@/components/dashboard-icons";
import { Card } from "@/components/ui/card";
import { navigationGroups } from "@/lib/crm-navigation";
import { cn } from "@/lib/utils";
import { useAuth, ROLE_LABELS, type Role } from "@/lib/auth-context";
import { filterVisibleNavigationGroups, getAllowedRolesForPath } from "@/lib/rbac";
import { RouteGuard } from "@/components/route-guard";

type DashboardShellProps = {
  children: ReactNode;
};

export function DashboardShell({ children }: DashboardShellProps) {
  const pathname = usePathname();
  const router = useRouter();
  const { activeRole, session, switchRole } = useAuth();
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [accountOpen, setAccountOpen] = useState(false);
  const [showRoleOptions, setShowRoleOptions] = useState(false);
  const [switchingRole, setSwitchingRole] = useState<string | null>(null);
  const [switchNotice, setSwitchNotice] = useState<string | null>(null);
  const [hash, setHash] = useState("");

  useEffect(() => {
    const updateHash = () => setHash(window.location.hash);

    updateHash();
    window.addEventListener("hashchange", updateHash);

    return () => window.removeEventListener("hashchange", updateHash);
  }, []);

  useEffect(() => {
    if (!switchNotice) {
      return;
    }

    const timeout = window.setTimeout(() => setSwitchNotice(null), 2400);
    return () => window.clearTimeout(timeout);
  }, [switchNotice]);

  const currentPath = `${pathname}${hash}`;
  const allowedRoles = useMemo(() => getAllowedRolesForPath(pathname), [pathname]);
  const visibleNavigationGroups = useMemo(() => filterVisibleNavigationGroups(activeRole, navigationGroups), [activeRole]);
  const isDemoAccount = session?.user.isDemoAccount ?? false;
  const availableRoles = session?.availableRoles ?? [];
  const sidebarWidth = sidebarCollapsed ? "5rem" : "18rem";
  const shellStyle = { "--sidebar-width": sidebarWidth } as CSSProperties;

  const isActive = (href: string, isFirstItem: boolean) => {
    const [baseHref, fragment] = href.split("#");
    const isBooqPage = pathname === "/boq";
    const isBooqDetailPage = pathname.startsWith("/boq/") && !pathname.includes("/", 6);
    const isBooqBreakdownPage = pathname.startsWith("/boq/") && pathname.endsWith("/breakdown");
    const isBooqRevisionPage = pathname.startsWith("/boq/") && pathname.endsWith("/revise");
    const isBooqPricingPage = pathname.startsWith("/boq/") && pathname.endsWith("/pricing");
    const isBooqQuotationPage = pathname.startsWith("/boq/") && pathname.endsWith("/quotation");
    const isQuotationDetailPage = pathname.startsWith("/quotations/");
    const isPurchaseRequestCreatePage = pathname === "/purchase-requests/new";
    const isPurchaseRequestApprovalsPage = pathname === "/purchase-requests/approvals" || pathname.startsWith("/purchase-requests/approvals/");
    const isPurchaseRequestDetailPage =
      pathname.startsWith("/purchase-requests/") && !isPurchaseRequestCreatePage && !isPurchaseRequestApprovalsPage && pathname !== "/purchase-requests";
    const isVendorPoCreatePage = pathname === "/vendor-po/new";
    const isVendorPoApprovalsPage = pathname === "/vendor-po/approvals" || pathname.startsWith("/vendor-po/approvals/");
    const isVendorPoDetailPage =
      pathname.startsWith("/vendor-po/") && !isVendorPoCreatePage && !isVendorPoApprovalsPage && pathname !== "/vendor-po";
    const isApprovalDetailPage = pathname.startsWith("/approvals/") && pathname !== "/approvals";
    const isRapApprovalDetailPage = pathname.startsWith("/rap-approvals/") && pathname !== "/rap-approvals";
    const isCustomerPoDetailPage = pathname.startsWith("/opportunities/") && pathname.endsWith("/customer-po");
    const isRapOperationalReviewPage = pathname.startsWith("/rap/") && pathname.endsWith("/operational-review");
    const isRapDetailPage = pathname.startsWith("/rap/") && pathname !== "/rap" && !pathname.endsWith("/operational-review");
    const isProcurementDetailPage = pathname.startsWith("/procurement/") && pathname !== "/procurement";

    if (isBooqPage || isBooqDetailPage || isBooqBreakdownPage || isBooqRevisionPage) {
      return baseHref === "/opportunities";
    }

    if (isBooqPricingPage) {
      return baseHref === "/sales-pricing";
    }

    if (isBooqQuotationPage) {
      return baseHref === "/quotation";
    }

    if (isQuotationDetailPage) {
      return baseHref === "/opportunities";
    }

    if (pathname === "/quotation" && hash === "#drafts") {
      return baseHref === "/opportunities";
    }

    if (isPurchaseRequestDetailPage) {
      return baseHref === "/purchase-requests";
    }

    if (isPurchaseRequestCreatePage) {
      return baseHref === "/purchase-requests";
    }

    if (isPurchaseRequestApprovalsPage) {
      return baseHref === "/purchase-requests";
    }

    if (isVendorPoCreatePage) {
      return baseHref === "/vendor-po";
    }

    if (isVendorPoApprovalsPage) {
      return baseHref === "/vendor-po/approvals";
    }

    if (isVendorPoDetailPage) {
      return baseHref === "/vendor-po";
    }

    if (isApprovalDetailPage) {
      return baseHref === "/approvals";
    }

    if (isRapApprovalDetailPage) {
      return baseHref === "/rap-approvals";
    }

    if (isCustomerPoDetailPage) {
      return baseHref === "/opportunities";
    }

    if (isRapOperationalReviewPage) {
      return baseHref === "/rap";
    }

    if (isRapDetailPage) {
      return baseHref === "/opportunities";
    }

    if (isProcurementDetailPage) {
      return baseHref === "/procurement";
    }

    if (fragment) {
      if (pathname !== baseHref) {
        return false;
      }

      if (!hash) {
        return isFirstItem;
      }

      return currentPath === href;
    }

    return pathname === baseHref;
  };

  function handleSwitchRole(role: Role) {
    if (!isDemoAccount || role === activeRole) {
      setShowRoleOptions(false);
      return;
    }

    setSwitchingRole(role);
    switchRole(role);
    setShowRoleOptions(false);
    setAccountOpen(false);
    setSwitchNotice(`Beralih ke peran: ${ROLE_LABELS[role]}`);
    window.setTimeout(() => setSwitchingRole(null), 300);
  }

  return (
    <RouteGuard allowedRoles={allowedRoles}>
      <div className="h-[125vh] overflow-hidden bg-transparent" style={shellStyle}>
        <button
          type="button"
          aria-label="Open sidebar"
          onClick={() => setMobileOpen((value) => !value)}
          className="fixed left-4 top-4 z-40 inline-flex rounded-full border border-border bg-background p-2 text-foreground shadow-sm transition hover:bg-accent lg:hidden"
        >
          <MenuIcon className="h-5 w-5" />
        </button>

        {mobileOpen ? (
          <button
            type="button"
            aria-label="Close sidebar"
            onClick={() => setMobileOpen(false)}
            className="fixed inset-0 z-40 bg-slate-950/50 backdrop-blur-sm lg:hidden"
          />
        ) : null}

        <div className="h-full">
        <aside
          className={cn(
            "fixed top-0 left-0 z-50 flex w-72 h-[125vh] flex-col border-r border-border/70 bg-[linear-gradient(180deg,rgba(255,255,255,0.98),rgba(245,249,255,0.96))] shadow-[0_20px_60px_rgba(15,23,42,0.08)] backdrop-blur-xl transition-all duration-300 lg:w-[var(--sidebar-width)] lg:translate-x-0 lg:overflow-y-auto",
            mobileOpen ? "translate-x-0" : "-translate-x-full",
          )}
        >
          <div className="flex h-16 shrink-0 items-center justify-between gap-3 border-b border-border/70 bg-background/95 px-4 text-foreground backdrop-blur-xl">
            <div className={cn("min-w-0", sidebarCollapsed ? "lg:hidden" : "lg:block")}> 
              <Image
                src="/spekta-tech-nusantara-logo.png"
                alt="Spekta Tech Nusantara"
                width={520}
                height={166}
                priority
                className="h-auto w-full max-w-[13rem] object-contain"
              />
            </div>

            <div className="flex items-center gap-2">
              <button
                type="button"
                aria-label="Toggle sidebar"
                onClick={() => setSidebarCollapsed((value) => !value)}
                className="hidden rounded-full border border-border bg-background p-2 text-foreground transition hover:bg-accent lg:inline-flex"
              >
                {sidebarCollapsed ? (
                  <ChevronRightIcon className="h-4 w-4" />
                ) : (
                  <ChevronLeftIcon className="h-4 w-4" />
                )}
              </button>
              <button
                type="button"
                aria-label="Close sidebar"
                onClick={() => setMobileOpen(false)}
                className="rounded-full border border-border bg-background p-2 text-foreground transition hover:bg-accent lg:hidden"
              >
                <ChevronLeftIcon className="h-4 w-4" />
              </button>
            </div>
          </div>

          <nav className="flex-1 space-y-4 overflow-y-auto p-3">
            {visibleNavigationGroups.map((group) => (
              <div key={group.label} className="space-y-2">
                {group.label ? (
                  <p
                    className={cn(
                      "px-3 text-[11px] font-semibold uppercase tracking-[0.24em] text-muted-foreground",
                      sidebarCollapsed ? "lg:hidden" : "lg:block",
                    )}
                  >
                    {group.label}
                  </p>
                ) : null}

                <div className="space-y-1">
                  {group.items.map((item, index) => {
                    const Icon = item.icon;
                    const active = isActive(item.href, index === 0);

                    return (
                      <Link
                        key={item.href}
                        href={item.href}
                        onClick={() => setMobileOpen(false)}
                        className={cn(
                          "group flex items-center gap-3 rounded-2xl px-3 py-3 text-sm font-medium transition-all",
                          active
                            ? "bg-primary text-primary-foreground shadow-sm"
                            : "text-foreground/75 hover:bg-accent hover:text-foreground",
                          sidebarCollapsed ? "lg:justify-center lg:px-0" : "lg:px-3",
                        )}
                        title={sidebarCollapsed ? item.name : undefined}
                      >
                        <Icon className="h-5 w-5 shrink-0" />
                        <span className={cn("truncate", sidebarCollapsed ? "lg:hidden" : "lg:inline")}>{item.name}</span>
                      </Link>
                    );
                  })}
                </div>
              </div>
            ))}
          </nav>
        </aside>

          <div className="flex h-full min-w-0 flex-1 flex-col lg:pl-[var(--sidebar-width)]">
          <header className="fixed top-0 right-0 z-30 flex h-16 items-center border-b border-border/70 bg-background/95 text-foreground backdrop-blur-xl lg:left-[var(--sidebar-width)]">
            <div className="flex flex-1 items-center justify-between gap-4 px-4 md:px-6 lg:px-8">
              <div className="flex-1" />

              <div className="relative flex items-center gap-2">
                <button
                  type="button"
                  aria-label="Open account menu"
                  onClick={() => {
                    setAccountOpen((value) => !value);
                    setShowRoleOptions(false);
                  }}
                  className="flex items-center gap-2 rounded-full border border-border bg-background px-3 py-2 text-sm font-medium text-foreground transition hover:bg-accent"
                >
                  <span className="flex h-8 w-8 items-center justify-center rounded-full bg-primary text-primary-foreground">
                    <UserIcon className="h-4 w-4" />
                  </span>
                  <span className="hidden sm:inline">{activeRole ? ROLE_LABELS[activeRole] : "Account"}</span>
                  <ChevronDownIcon className="hidden h-4 w-4 sm:inline" />
                </button>

                {accountOpen ? (
                  <button
                    type="button"
                    aria-label="Close account menu"
                    onClick={() => setAccountOpen(false)}
                    className="fixed inset-0 z-40 bg-transparent"
                  />
                ) : null}

                {accountOpen ? (
                  <Card className="absolute right-0 top-16 z-50 w-[18rem] overflow-hidden border-border/80 bg-card text-card-foreground">
                    <div className="border-b border-border/70 px-4 py-4">
                      <p className="text-sm font-semibold">{session?.user.name ?? "Demo User"}</p>
                      <p className="text-xs text-muted-foreground">{session?.user.email ?? "demo@spektatech.com"}</p>
                      {isDemoAccount ? (
                        <div className="mt-2">
                          <button
                            type="button"
                            onClick={() => setShowRoleOptions(!showRoleOptions)}
                            className="flex w-full items-center justify-between text-left"
                          >
                            <p className="text-xs uppercase tracking-[0.2em] text-muted-foreground">
                              Active role:{" "}
                              <span className="font-semibold text-foreground">
                                {activeRole ? ROLE_LABELS[activeRole] : "-"}
                              </span>
                            </p>
                            <ChevronDownIcon
                              className={cn(
                                "h-3 w-3 text-muted-foreground transition-transform",
                                showRoleOptions && "rotate-180",
                              )}
                            />
                          </button>
                          {showRoleOptions ? (
                            <div className="mt-3 space-y-1">
                              {availableRoles.map((role) => {
                                const active = activeRole === role;
                                const pending = switchingRole === role;
                                return (
                                  <button
                                    key={role}
                                    type="button"
                                    onClick={() => handleSwitchRole(role)}
                                    className={cn(
                                      "flex w-full items-center justify-between gap-3 rounded-xl px-3 py-2.5 text-sm transition",
                                      active
                                        ? "bg-accent text-foreground"
                                        : "hover:bg-accent/50",
                                    )}
                                  >
                                    <span className="flex items-center gap-2">
                                      <span
                                        className={cn(
                                          "flex h-4 w-4 items-center justify-center rounded-full border",
                                          active
                                            ? "border-primary bg-primary"
                                            : "border-border bg-background",
                                        )}
                                      >
                                        {active ? (
                                          <span className="h-2 w-2 rounded-full bg-white" />
                                        ) : null}
                                      </span>
                                      <span>{ROLE_LABELS[role]}</span>
                                    </span>
                                    {active ? (
                                      <span className="rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
                                        Aktif
                                      </span>
                                    ) : null}
                                    {pending ? (
                                      <span className="h-3 w-3 animate-spin rounded-full border-2 border-primary/30 border-t-primary" />
                                    ) : null}
                                  </button>
                                );
                              })}
                            </div>
                          ) : null}
                        </div>
                      ) : (
                        <p className="mt-2 text-xs uppercase tracking-[0.2em] text-muted-foreground">
                          Active role: {activeRole ? ROLE_LABELS[activeRole] : "-"}
                        </p>
                      )}
                    </div>
                    <div className="p-2">
                      <Link
                        href="/admin#settings"
                        className="flex items-center gap-3 rounded-xl px-3 py-3 text-sm font-medium transition hover:bg-accent"
                      >
                        <UserIcon className="h-4 w-4" />
                        Settings
                      </Link>
                      <button
                        type="button"
                        className="flex w-full items-center gap-3 rounded-xl px-3 py-3 text-sm font-medium text-red-600 transition hover:bg-red-50"
                        onClick={() => router.push("/login")}
                      >
                        <LogOutIcon className="h-4 w-4" />
                        Logout
                      </button>
                    </div>
                  </Card>
                ) : null}
              </div>
            </div>
          </header>

          <main className="flex-1 overflow-y-auto pt-16">
            <div className="mx-auto w-full max-w-[1600px] px-4 py-5 md:px-6 md:py-8 lg:px-8">
              {children}
            </div>
          </main>

          <footer className="border-t border-border/70 bg-card/70 px-4 py-1.5 backdrop-blur md:px-6 lg:px-8">
            <div className="flex items-center justify-center text-sm text-black">
              Copyright (c) 2026 Project Tender &amp; CRM | PT Spekta Tech Nusantara. All Right Reserved
            </div>
          </footer>
        </div>
      </div>
        {switchNotice ? (
          <div className="fixed bottom-4 right-4 z-50 w-[18rem] rounded-2xl border border-sky-200 bg-sky-50 px-4 py-3 text-sm text-sky-900 shadow-[0_16px_50px_rgba(14,165,233,0.18)]">
            <p className="font-semibold">Role switched</p>
            <p className="mt-1">{switchNotice}</p>
          </div>
        ) : null}
      </div>
    </RouteGuard>
  );
}
