"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { Icon, type IconName } from "@/components/Icon";
import { LanguageToggle, ThemeToggle, useT } from "@/components/providers";
import { api } from "@/lib/client";

export interface NavItem {
  href: string;
  label: string;
  icon: IconName;
}

export interface ShellUser {
  fullName: string;
  username: string;
  isDemo: boolean;
  mustChangePassword: boolean;
  roles: string[];
}

export function Shell({ user, nav, children }: { user: ShellUser; nav: NavItem[]; children: React.ReactNode }) {
  const [open, setOpen] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [collapsed, setCollapsed] = useState(false);
  const pathname = usePathname();
  const router = useRouter();
  const [loggingOut, setLoggingOut] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);
  const { t } = useT();

  useEffect(() => {
    setCollapsed(localStorage.getItem("bousla_sidebar") === "collapsed");
  }, []);

  useEffect(() => {
    function onDocClick(e: MouseEvent) {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) setMenuOpen(false);
    }
    document.addEventListener("mousedown", onDocClick);
    return () => document.removeEventListener("mousedown", onDocClick);
  }, []);

  function toggleCollapsed() {
    const next = !collapsed;
    setCollapsed(next);
    localStorage.setItem("bousla_sidebar", next ? "collapsed" : "expanded");
  }

  /** Dark-mode toggle (same persistence as the login-page toggle + server preference). */
  function toggleTheme() {
    const dark = document.documentElement.classList.toggle("dark");
    const theme = dark ? "dark" : "light";
    localStorage.setItem("bousla_theme", theme);
    document.cookie = `bousla_theme=${theme}; path=/; max-age=31536000; samesite=strict`;
    void api("/api/auth/preferences", "PUT", { theme }).catch(() => undefined);
  }

  /** Language switch: flips direction via the locale cookie + server refresh. */
  function switchLanguage() {
    const next = t.common.language === "English" ? "en" : "ar";
    document.cookie = `bousla_locale=${next}; path=/; max-age=31536000; samesite=strict`;
    void api("/api/auth/preferences", "PUT", { locale: next }).catch(() => undefined);
    router.refresh();
    router.refresh();
  }

  async function logout() {
    setLoggingOut(true);
    setMenuOpen(false);
    await api("/api/auth/logout", "POST");
    router.push("/login");
    router.refresh();
  }

  const initials = user.fullName.replace(/^(DEMO|دِيمُو)\s*/i, "").trim().slice(0, 1) || "؟";

  const sidebarInner = (
    <div className="flex h-full flex-col bg-bousla-950 text-bousla-100">
      <div className={`flex items-center py-4 ${collapsed ? "flex-col gap-2 px-2" : "gap-3 px-5"} transition-all`}>
        <span className="h-12 w-12 shrink-0 overflow-hidden rounded-xl bg-[#f3efe6] ring-1 ring-sand-400/40">
          <Image src="/logo.png" alt="بوصلة" width={48} height={48} className="h-full w-full object-cover" priority />
        </span>
        {!collapsed && (
          <div className="min-w-0 flex-1">
            <p className="truncate text-base font-bold text-white">{t.common.appName}</p>
            <p className="truncate text-[11px] text-sand-400/90">{t.common.tagline}</p>
          </div>
        )}
        <button
          onClick={toggleCollapsed}
          title={collapsed ? t.common.openMenu : t.common.collapse}
          aria-label={collapsed ? t.common.openMenu : t.common.collapse}
          aria-expanded={!collapsed}
          className="hidden shrink-0 rounded-lg p-1.5 text-bousla-300/70 transition hover:bg-white/5 hover:text-white lg:block"
        >
          <Icon name="menu" className="h-5 w-5" />
        </button>
      </div>

      <nav className="flex-1 space-y-1 overflow-y-auto px-3 py-2" aria-label={t.common.mainNav}>
        {nav.map((item) => {
          const active = pathname === item.href || (item.href !== "/dashboard" && pathname.startsWith(item.href));
          return (
            <Link
              key={item.href}
              href={item.href}
              onClick={() => setOpen(false)}
              title={item.label}
              className={`flex items-center rounded-lg text-sm font-semibold transition ${collapsed ? "justify-center px-2 py-2.5" : "gap-3 px-3 py-2.5"} ${
                active ? "bg-bousla-600/30 text-white ring-1 ring-bousla-400/30" : "text-bousla-200/70 hover:bg-white/5 hover:text-white"
              }`}
            >
              <Icon name={item.icon} className="h-5 w-5 shrink-0" />
              {!collapsed && item.label}
            </Link>
          );
        })}

        {/* Appearance, language, and sign-out live in the navigation (owner request) */}
        <div className="border-t border-white/10 pt-2 mt-2">
          <button
            onClick={toggleTheme}
            title={t.common.theme}
            className={`flex w-full items-center rounded-lg text-sm font-semibold text-bousla-200/70 transition hover:bg-white/5 hover:text-white ${collapsed ? "justify-center px-2 py-2.5" : "gap-3 px-3 py-2.5"}`}
          >
            <Icon name="sparkles" className="h-5 w-5 shrink-0" />
            {!collapsed && t.common.theme}
          </button>
          <button
            onClick={switchLanguage}
            title={t.common.language}
            className={`flex w-full items-center rounded-lg text-sm font-semibold text-bousla-200/70 transition hover:bg-white/5 hover:text-white ${collapsed ? "justify-center px-2 py-2.5" : "gap-3 px-3 py-2.5"}`}
          >
            <Icon name="academic" className="h-5 w-5 shrink-0" />
            {!collapsed && t.common.language}
          </button>
          <button
            onClick={logout}
            disabled={loggingOut}
            title={t.common.logout}
            className={`flex w-full items-center rounded-lg text-sm font-semibold text-red-400/80 transition hover:bg-red-500/10 hover:text-red-300 disabled:opacity-50 ${collapsed ? "justify-center px-2 py-2.5" : "gap-3 px-3 py-2.5"}`}
          >
            <Icon name="logout" className="h-5 w-5 shrink-0" />
            {!collapsed && t.common.logout}
          </button>
        </div>
      </nav>

      <div className="border-t border-white/10 p-3">
        {/* Account dropdown: identity + profile/notifications/messages/settings/logout */}
        <div className="relative" ref={menuRef}>
          <button
            onClick={() => setMenuOpen((v) => !v)}
            aria-label={t.common.accountMenu}
            aria-expanded={menuOpen}
            className={`flex w-full items-center rounded-lg text-start transition hover:bg-white/5 ${collapsed ? "justify-center p-1.5" : "gap-3 p-2"}`}
          >
            <span className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-bousla-700 text-sm font-bold text-white">
              {initials}
            </span>
            {!collapsed && (
              <span className="min-w-0 flex-1 text-start" dir="auto">
                <span className="block truncate text-sm font-semibold text-white">{user.fullName}</span>
                <span className="block truncate text-[11px] text-bousla-300/70" dir="ltr">{user.username}</span>
              </span>
            )}
            {!collapsed && <Icon name="chevronDown" className={`h-4 w-4 shrink-0 text-bousla-300/70 transition ${menuOpen ? "rotate-180" : ""}`} />}
          </button>

          {menuOpen && (
            <div className="absolute bottom-full z-50 mb-2 w-60 overflow-hidden rounded-xl border border-slate-200 bg-white py-1 shadow-xl start-0">
              <div className="border-b border-slate-100 px-4 py-2.5">
                <p className="truncate text-sm font-bold text-slate-800" dir="auto">{user.fullName}</p>
                <p className="truncate text-[11px] text-slate-400" dir="ltr">{user.username}</p>
              </div>
              <Link href="/dashboard/my-profile" onClick={() => setMenuOpen(false)} className="flex items-center gap-2.5 px-4 py-2 text-sm text-slate-700 transition hover:bg-slate-50">
                <Icon name="user" className="h-4 w-4" /> {t.myProfile.title}
              </Link>
              <Link href="/dashboard/notifications" onClick={() => setMenuOpen(false)} className="flex items-center gap-2.5 px-4 py-2 text-sm text-slate-700 transition hover:bg-slate-50">
                <Icon name="bell" className="h-4 w-4" /> {t.common.notifications}
              </Link>
              <Link href="/dashboard/messages" onClick={() => setMenuOpen(false)} className="flex items-center gap-2.5 px-4 py-2 text-sm text-slate-700 transition hover:bg-slate-50">
                <Icon name="mail" className="h-4 w-4" /> {t.common.messages}
              </Link>
              <Link href="/dashboard/profile" onClick={() => setMenuOpen(false)} className="flex items-center gap-2.5 px-4 py-2 text-sm text-slate-700 transition hover:bg-slate-50">
                <Icon name="cog" className="h-4 w-4" /> {t.common.accountSettings}
              </Link>
            </div>
          )}
        </div>

        {user.isDemo && !collapsed && (
          <p className="mt-3 rounded-md bg-sand-500/15 px-2.5 py-1.5 text-center text-[11px] font-bold text-sand-400">
            {t.common.demoBadge}
          </p>
        )}
      </div>
    </div>
  );

  return (
    <div className="min-h-screen bg-slate-100">
      {/* Desktop sidebar — inline-start follows RTL/LTR automatically */}
      <aside className={`fixed inset-y-0 start-0 z-30 hidden transition-all duration-200 lg:block ${collapsed ? "w-20" : "w-72"}`}>
        {sidebarInner}
      </aside>

      {/* Mobile top bar */}
      <header className="sticky top-0 z-20 flex items-center justify-between border-b border-slate-200 bg-white/90 px-4 py-3 backdrop-blur lg:hidden">
        <div className="flex items-center gap-2.5">
          <span className="h-9 w-9 overflow-hidden rounded-lg bg-[#f3efe6] ring-1 ring-sand-400/40">
            <Image src="/logo.png" alt="بوصلة" width={36} height={36} className="h-full w-full object-cover" priority />
          </span>
          <span className="font-bold text-slate-900">{t.common.appName}</span>
        </div>
        <div className="flex items-center gap-1">
          <ThemeToggle className="text-slate-600" />
          <LanguageToggle className="text-slate-600" />
          <button
            onClick={() => setOpen(true)}
            aria-label={t.common.openMenu}
            className="grid h-10 w-10 place-items-center rounded-lg border border-slate-200 text-slate-600"
          >
            <Icon name="menu" className="h-5 w-5" />
          </button>
        </div>
      </header>

      {/* Mobile drawer */}
      {open && (
        <div className="fixed inset-0 z-40 lg:hidden" role="dialog" aria-modal="true">
          <div className="absolute inset-0 bg-slate-900/50" onClick={() => setOpen(false)} />
          <div className="absolute inset-y-0 start-0 w-72 max-w-[85%] shadow-2xl">{sidebarInner}</div>
        </div>
      )}

      <main className={`px-4 py-6 sm:px-6 lg:px-8 lg:py-8 transition-all duration-200 ${collapsed ? "lg:ms-20" : "lg:ms-72"}`}>
        {children}
      </main>
    </div>
  );
}
