"use client";

import { useEffect, useState } from "react";
import {
  LayoutDashboard, ReceiptText, UserPlus, Wallet, BarChart3,
  UsersRound, History, Settings, LogOut, Menu, X, ChevronLeft,
  GraduationCap, Bell, Network, Building2,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { cn } from "@/lib/utils";
import { ROLE_AR, getActiveSchoolId, setActiveSchoolId, apiFetch } from "@/lib/client-utils";
import { SchoolSettingsDTO, SchoolDTO } from "@/lib/types";
import { AnimatePresence, motion } from "framer-motion";

export type ViewKey =
  | "schools" | "dashboard" | "payment" | "students" | "classes" | "finance"
  | "reports" | "users" | "audit" | "settings";

interface NavItem {
  key: ViewKey;
  label: string;
  labelEn: string;
  icon: React.ComponentType<{ className?: string }>;
  roles: string[];
}

export const NAV_ITEMS: NavItem[] = [
  { key: "schools", label: "إدارة المدارس", labelEn: "Schools", icon: Building2, roles: ["SUPER_ADMIN"] },
  { key: "dashboard", label: "لوحة المعلومات", labelEn: "Dashboard", icon: LayoutDashboard, roles: ["SUPER_ADMIN", "ADMIN", "ACCOUNTANT", "STAFF"] },
  { key: "payment", label: "الدفع المباشر", labelEn: "Quick Payment", icon: ReceiptText, roles: ["SUPER_ADMIN", "ADMIN", "ACCOUNTANT"] },
  { key: "students", label: "تسجيل الطلبة والبحث", labelEn: "Students", icon: UserPlus, roles: ["SUPER_ADMIN", "ADMIN", "ACCOUNTANT", "STAFF"] },
  { key: "classes", label: "الصفوف والشعب", labelEn: "Classes & Sections", icon: Network, roles: ["SUPER_ADMIN", "ADMIN", "STAFF"] },
  { key: "finance", label: "الإيرادات والمصروفات", labelEn: "Income & Expenses", icon: Wallet, roles: ["SUPER_ADMIN", "ADMIN", "ACCOUNTANT"] },
  { key: "reports", label: "التقارير", labelEn: "Reports", icon: BarChart3, roles: ["SUPER_ADMIN", "ADMIN", "ACCOUNTANT"] },
  { key: "users", label: "إدارة المستخدمين", labelEn: "Users", icon: UsersRound, roles: ["SUPER_ADMIN", "ADMIN"] },
  { key: "audit", label: "سجل الحركات", labelEn: "Audit Log", icon: History, roles: ["SUPER_ADMIN", "ADMIN"] },
  { key: "settings", label: "إعدادات المدرسة", labelEn: "Settings", icon: Settings, roles: ["SUPER_ADMIN", "ADMIN"] },
];

interface AppShellProps {
  user: { id: string; username: string; fullName: string; role: string; allowedViews?: string[] | null };
  settings: SchoolSettingsDTO | null;
  currentView: ViewKey;
  onViewChange: (view: ViewKey) => void;
  onLogout: () => void;
  announcementsCount: number;
  children: React.ReactNode;
}

/** هل يملك المستخدم صلاحية الوصول لصفحة معينة حسب الدور والصفحات المسموحة؟ */
export function canAccessView(
  user: { role: string; allowedViews?: string[] | null },
  key: string
): boolean {
  const item = NAV_ITEMS.find((i) => i.key === key);
  if (!item) return false;
  if (user.role === "SUPER_ADMIN") return true; // مدير النظام العام يرى كل الصفحات
  if (!item.roles.includes(user.role)) return false;
  // تقييد الصفحات: null/فارغة = الافتراضي حسب الدور، وإلا فالقائمة المسموحة فقط
  if (user.allowedViews && user.allowedViews.length > 0) {
    return user.allowedViews.includes(key);
  }
  return true;
}

export default function AppShell({
  user, settings, currentView, onViewChange, onLogout, announcementsCount, children,
}: AppShellProps) {
  const [sidebarOpen, setSidebarOpen] = useState(true); // للحاسوب: طي/فتح
  const [mobileOpen, setMobileOpen] = useState(false); // للهاتف: درج جانبي
  const [schools, setSchools] = useState<SchoolDTO[]>([]);
  const isSuper = user.role === "SUPER_ADMIN";

  // مدير النظام العام: قائمة اختيار المدرسة الفعالة
  useEffect(() => {
    if (!isSuper) return;
    apiFetch<{ schools: SchoolDTO[]; activeSchoolId: string | null }>("/api/schools")
      .then((d) => {
        setSchools(d.schools.filter((s) => s.isActive));
        // ضبط افتراضي أول مرة: أول مدرسة نشطة
        if (!getActiveSchoolId() && d.activeSchoolId) setActiveSchoolId(d.activeSchoolId);
      })
      .catch(() => undefined);
  }, [isSuper]);

  function switchSchool(id: string) {
    setActiveSchoolId(id);
    window.location.reload();
  }

  const items = NAV_ITEMS.filter((item) => canAccessView(user, item.key));
  const mobilePrimaryItems = ["dashboard", "payment", "students", "finance", "reports"]
    .map((key) => items.find((item) => item.key === key))
    .filter((item): item is NavItem => Boolean(item));
  const schoolName = settings?.nameAr || "المدرسة الأهلية";
  const logo = settings?.logoData || null;
  const activeItem = items.find((i) => i.key === currentView);

  const sidebarContent = (onNavigate?: () => void) => (
    <div className="flex flex-col h-full">
      {/* الشعار واسم المدرسة */}
      <div className="flex items-center gap-3 px-4 py-5 border-b border-sidebar-border shrink-0">
        {logo ? (
          <img src={logo} alt="شعار المدرسة" className="w-10 h-10 rounded-xl object-cover bg-white/90 p-0.5" />
        ) : (
          <div className="w-10 h-10 rounded-xl bg-sidebar-primary/20 text-sidebar-primary flex items-center justify-center shrink-0">
            <GraduationCap className="w-6 h-6" />
          </div>
        )}
        {sidebarOpen && (
          <div className="min-w-0 flex-1">
            <p className="font-bold text-sm leading-tight truncate">{schoolName}</p>
            <p className="text-[11px] text-sidebar-foreground/60 truncate">نظام الإدارة المالية والطلابية</p>
          </div>
        )}
        {/* زر الطي للحاسوب */}
        <Button
          variant="ghost"
          size="icon"
          className="hidden lg:inline-flex text-sidebar-foreground/70 hover:bg-sidebar-accent hover:text-sidebar-foreground"
          onClick={() => setSidebarOpen(!sidebarOpen)}
          aria-label={sidebarOpen ? "طي القائمة الجانبية" : "فتح القائمة الجانبية"}
        >
          <ChevronLeft className={cn("w-4 h-4 transition-transform", !sidebarOpen && "rotate-180")} />
        </Button>
        {/* زر إغلاق للهاتف */}
        <Button
          variant="ghost"
          size="icon"
          className="lg:hidden text-sidebar-foreground/70"
          onClick={() => setMobileOpen(false)}
          aria-label="إغلاق القائمة"
        >
          <X className="w-4 h-4" />
        </Button>
      </div>

      {/* عناصر التنقل */}
      <nav className="flex-1 overflow-y-auto py-3 px-2 space-y-1" aria-label="التنقل الرئيسي">
        {items.map((item) => {
          const Icon = item.icon;
          const active = currentView === item.key;
          return (
            <button
              key={item.key}
              onClick={() => {
                onViewChange(item.key);
                onNavigate?.();
              }}
              className={cn(
                "w-full flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors text-right",
                active
                  ? "bg-sidebar-primary text-sidebar-primary-foreground shadow-sm"
                  : "text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
              )}
              aria-current={active ? "page" : undefined}
              title={item.label}
            >
              <Icon className="w-[18px] h-[18px] shrink-0" />
              {sidebarOpen && (
                <span className="flex-1 flex flex-col items-start min-w-0">
                  <span className="truncate">{item.label}</span>
                  <span className="text-[10px] opacity-60 font-normal truncate" dir="ltr">{item.labelEn}</span>
                </span>
              )}
            </button>
          );
        })}
      </nav>

      {/* معلومات المستخدم + خروج */}
      <div className="border-t border-sidebar-border p-3 shrink-0">
        <div className={cn("flex items-center gap-3 rounded-lg px-2 py-2", !sidebarOpen && "justify-center px-0")}>
          <Avatar className="w-9 h-9 border border-sidebar-primary/40">
            <AvatarFallback className="bg-sidebar-primary/20 text-sidebar-primary text-sm font-bold">
              {user.fullName.charAt(0)}
            </AvatarFallback>
          </Avatar>
          {sidebarOpen && (
            <div className="flex-1 min-w-0">
              <p className="text-sm font-semibold truncate">{user.fullName}</p>
              <p className="text-[11px] text-sidebar-foreground/60">{ROLE_AR[user.role]}</p>
            </div>
          )}
        </div>
        <button
          onClick={onLogout}
          className={cn(
            "mt-1 w-full flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-sidebar-foreground/75 hover:bg-destructive/20 hover:text-red-300 transition-colors",
            !sidebarOpen && "justify-center px-0"
          )}
        >
          <LogOut className="w-[18px] h-[18px] shrink-0" />
          {sidebarOpen && <span>تسجيل الخروج</span>}
        </button>
      </div>
    </div>
  );

  return (
    <div className="min-h-screen flex bg-background">
      {/* الشريط الجانبي - الحاسوب */}
      <aside
        className={cn(
          "hidden lg:block bg-sidebar text-sidebar-foreground shrink-0 transition-all duration-300 sticky top-0 h-screen",
          sidebarOpen ? "w-64" : "w-[76px]"
        )}
      >
        {sidebarContent()}
      </aside>

      {/* درج الهاتف */}
      <AnimatePresence>
      {mobileOpen && (
        <motion.div className="lg:hidden fixed inset-0 z-50 flex" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
          <motion.div
            className="absolute inset-0 bg-black/50 backdrop-blur-sm"
            onClick={() => setMobileOpen(false)}
            aria-hidden
            initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
          />
          <motion.aside className="relative z-10 w-72 max-w-[85vw] bg-sidebar text-sidebar-foreground h-full shadow-2xl" initial={{ x: 36, opacity: 0.8 }} animate={{ x: 0, opacity: 1 }} exit={{ x: 36, opacity: 0.8 }} transition={{ duration: 0.22, ease: "easeOut" }}>
            {sidebarContent(() => setMobileOpen(false))}
          </motion.aside>
        </motion.div>
      )}
      </AnimatePresence>

      {/* المحتوى الرئيسي */}
      <div className="flex-1 flex flex-col min-w-0">
        {/* الشريط العلوي */}
        <header className="sticky top-0 z-40 bg-card/95 backdrop-blur border-b h-16 flex items-center gap-3 px-4 lg:px-6 shrink-0">
          <Button
            variant="ghost"
            size="icon"
            className="lg:hidden"
            onClick={() => setMobileOpen(true)}
            aria-label="فتح القائمة"
          >
            <Menu className="w-5 h-5" />
          </Button>
          <div className="min-w-0 flex-1">
            <h2 className="text-lg font-bold truncate">{activeItem?.label ?? "لوحة المعلومات"}</h2>
            <p className="text-xs text-muted-foreground truncate hidden sm:block">
              {activeItem?.labelEn} · {settings?.nameEn || "School Management"}
            </p>
          </div>
          <div className="flex items-center gap-2">
            {isSuper && schools.length > 0 && (
              <select
                aria-label="المدرسة الفعالة"
                className="h-9 rounded-md border bg-background text-sm px-2 max-w-[190px]"
                value={getActiveSchoolId() ?? schools[0]?.id ?? ""}
                onChange={(e) => switchSchool(e.target.value)}
              >
                {schools.map((s) => (
                  <option key={s.id} value={s.id}>{s.name}</option>
                ))}
              </select>
            )}
            <Button
              variant="ghost"
              size="icon"
              className="relative"
              onClick={() => onViewChange("dashboard")}
              aria-label="الإشعارات والتنبيهات"
              title="الإشعارات والتنبيهات"
            >
              <Bell className="w-5 h-5" />
              {announcementsCount > 0 && (
                <span className="absolute -top-0.5 -left-0.5 w-4 h-4 rounded-full bg-destructive text-white text-[10px] font-bold flex items-center justify-center">
                  {announcementsCount > 9 ? "9+" : announcementsCount}
                </span>
              )}
            </Button>
            <div className="hidden sm:flex items-center gap-2 text-sm">
              <div className="text-right">
                <p className="font-semibold leading-tight">{user.fullName}</p>
                <p className="text-xs text-muted-foreground">{ROLE_AR[user.role]}</p>
              </div>
              <Avatar className="w-9 h-9">
                <AvatarFallback className="bg-primary/10 text-primary font-bold">
                  {user.fullName.charAt(0)}
                </AvatarFallback>
              </Avatar>
            </div>
          </div>
        </header>

        <main className="flex-1 min-w-0 p-3 sm:p-4 lg:p-6 pb-24 lg:pb-6">
          <AnimatePresence mode="wait" initial={false}>
            <motion.div key={currentView} initial={{ opacity: 0, y: 9 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -5 }} transition={{ duration: 0.2, ease: "easeOut" }}>
              {children}
            </motion.div>
          </AnimatePresence>
        </main>

        {/* وصول سريع ملائم للهاتف؛ الصفحات الإضافية تبقى في القائمة الجانبية. */}
        <nav
          className="lg:hidden fixed inset-x-0 bottom-0 z-40 border-t bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/85 pb-[env(safe-area-inset-bottom)]"
          aria-label="التنقل السريع"
        >
          <div className="mx-auto grid max-w-xl" style={{ gridTemplateColumns: `repeat(${mobilePrimaryItems.length + 1}, minmax(0, 1fr))` }}>
            {mobilePrimaryItems.map((item) => {
              const Icon = item.icon;
              const active = currentView === item.key;
              return (
                <button
                  key={item.key}
                  type="button"
                  onClick={() => onViewChange(item.key)}
                  aria-current={active ? "page" : undefined}
                  className={cn(
                    "flex min-h-14 flex-col items-center justify-center gap-1 px-1 text-[10px] font-medium transition-colors",
                    active ? "text-primary" : "text-muted-foreground hover:text-foreground"
                  )}
                >
                  <Icon className="h-5 w-5" />
                  <span className="max-w-full truncate">{item.label}</span>
                </button>
              );
            })}
            <button
              type="button"
              onClick={() => setMobileOpen(true)}
              className="flex min-h-14 flex-col items-center justify-center gap-1 px-1 text-[10px] font-medium text-muted-foreground hover:text-foreground"
              aria-label="فتح جميع الصفحات"
            >
              <Menu className="h-5 w-5" />
              <span>المزيد</span>
            </button>
          </div>
        </nav>

        <footer className="mt-auto border-t py-3 px-4 lg:px-6 text-center text-xs text-muted-foreground pb-[calc(4.5rem+env(safe-area-inset-bottom))] lg:pb-[max(0.75rem,env(safe-area-inset-bottom))]">
          {settings?.nameAr || "المدرسة الأهلية"} · School Management System © {new Date().getFullYear()}
        </footer>
      </div>
    </div>
  );
}
