"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  Bell,
  BookUser,
  FileClock,
  FileText,
  Gauge,
  Handshake,
  HeartHandshake,
  LogOut,
  Menu,
  ReceiptText,
  ShieldCheck,
  SlidersHorizontal,
  UserRound,
  UsersRound,
  X
} from "lucide-react";
import { logoutAction } from "@/app/actions/auth";
import { IdleSessionGuard } from "@/components/dashboard/idle-session-guard";
import { SubmitButton } from "@/components/forms/submit-button";
import { cn } from "@/lib/utils";
import type { AppRole, Profile } from "@/types/domain";

const adminLinks = [
  { href: "/admin", label: "نظرة عامة", icon: Gauge },
  { href: "/admin/orphans", label: "الأيتام", icon: BookUser },
  { href: "/admin/donors", label: "المتبرعون والحسابات", icon: UsersRound },
  { href: "/admin/sponsorships", label: "الكفالات", icon: Handshake },
  { href: "/admin/payments", label: "دفعات المتبرعين", icon: HeartHandshake },
  { href: "/admin/transfers", label: "تحويلات الأيتام", icon: ReceiptText },
  { href: "/admin/notifications", label: "الإشعارات", icon: Bell },
  { href: "/admin/reports", label: "التقارير", icon: FileText },
  { href: "/admin/settings", label: "الإعدادات", icon: SlidersHorizontal },
  { href: "/admin/audit", label: "سجل التدقيق", icon: FileClock }
];

const donorLinks = [
  { href: "/donor", label: "نظرة عامة", icon: Gauge },
  { href: "/donor/orphans", label: "الحالات المرتبطة", icon: BookUser },
  { href: "/donor/transfers", label: "التحويلات والإيصالات", icon: ReceiptText },
  { href: "/donor/notifications", label: "الإشعارات", icon: Bell },
  { href: "/donor/profile", label: "الملف الشخصي", icon: UserRound },
  { href: "/donor/security", label: "كلمة المرور", icon: ShieldCheck }
];

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

export function DashboardShellClient({
  profile,
  role,
  idleMinutes,
  children
}: {
  profile: Profile;
  role: AppRole;
  idleMinutes: number;
  children: React.ReactNode;
}) {
  const pathname = usePathname();
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const closeButtonRef = useRef<HTMLButtonElement>(null);
  const openButtonRef = useRef<HTMLButtonElement>(null);
  const links = role === "admin" ? adminLinks : donorLinks;
  const homeHref = role === "admin" ? "/admin" : "/donor";
  const dashboardLabel = role === "admin" ? "لوحة إدارة الكفالة" : "بوابة المتبرع";
  const closeSidebar = useCallback(() => {
    setSidebarOpen(false);
    window.requestAnimationFrame(() => openButtonRef.current?.focus());
  }, []);

  useEffect(() => {
    if (!sidebarOpen) return;

    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    closeButtonRef.current?.focus();

    const closeOnEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape") closeSidebar();
    };
    window.addEventListener("keydown", closeOnEscape);

    return () => {
      document.body.style.overflow = previousOverflow;
      window.removeEventListener("keydown", closeOnEscape);
    };
  }, [closeSidebar, sidebarOpen]);

  return (
    <div className="min-h-dvh bg-[var(--background)]">
      <IdleSessionGuard minutes={idleMinutes} />

      {sidebarOpen ? (
        <button
          type="button"
          className="fixed inset-0 z-40 bg-black/55 lg:hidden"
          aria-label="إغلاق القائمة"
          onClick={closeSidebar}
        />
      ) : null}

      <aside
        id="dashboard-navigation"
        aria-label="لوحة التحكم"
        className={cn(
          "invisible fixed inset-y-0 right-0 z-50 flex w-[min(88vw,300px)] translate-x-full flex-col border-l border-white/10 bg-[#1b2623] text-white shadow-2xl transition-transform duration-200 ease-out lg:visible lg:w-[260px] lg:translate-x-0 lg:shadow-none",
          sidebarOpen && "visible translate-x-0"
        )}
      >
        <div className="flex h-16 shrink-0 items-center justify-between border-b border-white/10 px-4">
          <Link
            href={homeHref}
            onClick={closeSidebar}
            className="flex min-w-0 items-center gap-2 font-black"
          >
            <HeartHandshake size={22} className="shrink-0" aria-hidden />
            <span className="truncate">منصة كفالة</span>
          </Link>
          <button
            ref={closeButtonRef}
            type="button"
            onClick={closeSidebar}
            className="grid size-11 shrink-0 place-items-center rounded-md text-white/75 hover:bg-white/10 hover:text-white lg:hidden"
            aria-label="إغلاق القائمة"
          >
            <X size={21} aria-hidden />
          </button>
        </div>

        <nav className="min-h-0 flex-1 space-y-1 overflow-y-auto p-3" aria-label="صفحات لوحة التحكم">
          {links.map(({ href, label, icon: Icon }) => {
            const active = isActivePath(pathname, href);
            return (
              <Link
                key={href}
                href={href}
                onClick={closeSidebar}
                aria-current={active ? "page" : undefined}
                className={cn(
                  "flex min-h-11 items-center gap-3 rounded-md px-3 text-sm font-semibold text-white/72 transition hover:bg-white/10 hover:text-white",
                  active && "bg-white/14 text-white"
                )}
              >
                <Icon size={18} className="shrink-0" aria-hidden />
                <span className="min-w-0 leading-6">{label}</span>
              </Link>
            );
          })}
        </nav>

        <div className="shrink-0 border-t border-white/10 p-4">
          <p className="truncate text-sm font-bold">{profile.full_name}</p>
          <p className="mt-1 text-xs text-white/50">{role === "admin" ? "مسؤول النظام" : "متبرع"}</p>
          <form action={logoutAction} className="mt-4">
            <SubmitButton
              pendingText="جارٍ تسجيل الخروج..."
              variant="ghost"
              size="sm"
              className="w-full justify-start px-2 text-white/65 hover:bg-white/10 hover:text-white"
            >
              <LogOut size={17} aria-hidden />
              تسجيل الخروج
            </SubmitButton>
          </form>
        </div>
      </aside>

      <div className="min-w-0 lg:mr-[260px]">
        <header className="sticky top-0 z-30 flex h-16 items-center gap-3 border-b border-[var(--border)] bg-white/95 px-3 backdrop-blur sm:px-5 lg:static lg:px-6">
          <button
            ref={openButtonRef}
            type="button"
            className="grid size-11 shrink-0 place-items-center rounded-md border border-[var(--border)] bg-white text-[var(--ink)] hover:bg-[var(--surface-muted)] lg:hidden"
            aria-label="فتح القائمة"
            aria-controls="dashboard-navigation"
            aria-expanded={sidebarOpen}
            onClick={() => setSidebarOpen(true)}
          >
            <Menu size={21} aria-hidden />
          </button>
          <div className="min-w-0">
            <p className="truncate text-sm font-black text-[var(--ink)] lg:text-[var(--ink-soft)]">
              {dashboardLabel}
            </p>
            <p className="truncate text-xs text-[var(--ink-faint)] lg:hidden">{profile.full_name}</p>
          </div>
        </header>
        <main className="min-w-0 px-3 py-4 sm:px-5 sm:py-6 lg:px-8 lg:py-8">{children}</main>
      </div>
    </div>
  );
}
