'use client';

import {
  Activity,
  Award,
  BarChart3,
  Building2,
  Calendar,
  CheckSquare,
  ClipboardCheck,
  ClipboardList,
  FileText,
  GraduationCap,
  LogIn,
  LogOut,
  Menu,
  Settings,
  UserCircle2,
  Users,
  X,
} from 'lucide-react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
import { proxyFetch, type AuthMePayload } from '@/lib/proxy-client';

interface NavItem {
  label: string;
  href: string;
  section: 'core' | 'operations' | 'admin';
  requiredPermission?: string;
  icon:
    | 'activity'
    | 'students'
    | 'verify'
    | 'academics'
    | 'teachers'
    | 'routine'
    | 'notices'
    | 'attendance'
    | 'assignments'
    | 'results'
    | 'reports'
    | 'settings';
}

const NAV_ITEMS: NavItem[] = [
  { label: 'Overview', href: '/dashboard', section: 'core', icon: 'activity' },
  {
    label: 'Students',
    href: '/students',
    section: 'core',
    requiredPermission: 'student.verify',
    icon: 'students',
  },
  {
    label: 'Verification Queue',
    href: '/verifications',
    section: 'core',
    requiredPermission: 'student.verify',
    icon: 'verify',
  },
  {
    label: 'Teachers',
    href: '/teachers',
    section: 'core',
    requiredPermission: 'teacher.manage',
    icon: 'teachers',
  },
  {
    label: 'Academics',
    href: '/academics',
    section: 'core',
    requiredPermission: 'academic.structure.manage',
    icon: 'academics',
  },
  {
    label: 'Routine',
    href: '/routine',
    section: 'operations',
    icon: 'routine',
  },
  {
    label: 'Notices',
    href: '/notices',
    section: 'operations',
    icon: 'notices',
  },
  {
    label: 'Attendance',
    href: '/attendance',
    section: 'operations',
    icon: 'attendance',
  },
  {
    label: 'Assignments',
    href: '/assignments',
    section: 'operations',
    icon: 'assignments',
  },
  {
    label: 'Results',
    href: '/results',
    section: 'operations',
    icon: 'results',
  },
  {
    label: 'Reports',
    href: '/reports',
    section: 'admin',
    icon: 'reports',
  },
  {
    label: 'Settings',
    href: '/settings',
    section: 'admin',
    icon: 'settings',
  },
];

export interface AdminSessionContextValue {
  authenticated: boolean;
  sessionChecked: boolean;
  user: AuthMePayload['user'] | null;
  hasPermission: (permission: string) => boolean;
}

const AdminSessionContext = createContext<AdminSessionContextValue>({
  authenticated: false,
  sessionChecked: false,
  user: null,
  hasPermission: () => true,
});

export function useAdminSession() {
  return useContext(AdminSessionContext);
}

function NavIcon({ icon }: { icon: NavItem['icon'] }) {
  switch (icon) {
    case 'activity':
      return <Activity className="h-4 w-4 shrink-0" aria-hidden="true" />;
    case 'students':
      return <GraduationCap className="h-4 w-4 shrink-0" aria-hidden="true" />;
    case 'verify':
      return <ClipboardCheck className="h-4 w-4 shrink-0" aria-hidden="true" />;
    case 'academics':
      return <Building2 className="h-4 w-4 shrink-0" aria-hidden="true" />;
    case 'teachers':
      return <Users className="h-4 w-4 shrink-0" aria-hidden="true" />;
    case 'routine':
      return <Calendar className="h-4 w-4 shrink-0" aria-hidden="true" />;
    case 'notices':
      return <FileText className="h-4 w-4 shrink-0" aria-hidden="true" />;
    case 'attendance':
      return <CheckSquare className="h-4 w-4 shrink-0" aria-hidden="true" />;
    case 'assignments':
      return <ClipboardList className="h-4 w-4 shrink-0" aria-hidden="true" />;
    case 'results':
      return <Award className="h-4 w-4 shrink-0" aria-hidden="true" />;
    case 'reports':
      return <BarChart3 className="h-4 w-4 shrink-0" aria-hidden="true" />;
    case 'settings':
      return <Settings className="h-4 w-4 shrink-0" aria-hidden="true" />;
  }
}

export function AdminShell({ children }: { children: ReactNode }) {
  const pathname = usePathname() ?? '/';
  const router = useRouter();
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [authenticated, setAuthenticated] = useState<boolean>(false);
  const [sessionChecked, setSessionChecked] = useState<boolean>(false);
  const [user, setUser] = useState<AuthMePayload['user'] | null>(null);

  useEffect(() => {
    let cancelled = false;
    void fetch('/api/auth/session', { method: 'GET', cache: 'no-store' })
      .then(async (res) => {
        if (cancelled) return;
        setAuthenticated(res.ok);
        setSessionChecked(true);
        if (res.ok) {
          const me = await proxyFetch<AuthMePayload>('auth/me').catch(() => null);
          if (!cancelled && me?.success && me.data?.user) {
            setUser(me.data.user);
          }
        } else {
          setUser(null);
        }
      })
      .catch(() => {
        if (!cancelled) {
          setAuthenticated(false);
          setSessionChecked(true);
          setUser(null);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [pathname]);

  async function handleLogout() {
    await fetch('/api/auth/logout', { method: 'POST', cache: 'no-store' }).catch(() => null);
    setAuthenticated(false);
    setUser(null);
    router.push('/login');
  }

  function hasPermission(permission: string): boolean {
    if (!user) return true;
    return user.permissions.includes(permission) || user.roles.includes('SUPER_ADMIN');
  }

  const sections: Array<{ id: NavItem['section']; title: string }> = [
    { id: 'core', title: 'Core Management' },
    { id: 'operations', title: 'Academic Operations' },
    { id: 'admin', title: 'System' },
  ];

  return (
    <AdminSessionContext.Provider value={{ authenticated, sessionChecked, user, hasPermission }}>
      <div className="min-h-screen bg-[var(--saic-surface-muted)] text-[var(--saic-ink)] lg:flex">
        {drawerOpen && (
          <div
            className="fixed inset-0 z-30 bg-slate-900/40 lg:hidden"
            onClick={() => setDrawerOpen(false)}
            aria-hidden="true"
          />
        )}

        <aside
          aria-label="Primary sidebar"
          className={`fixed inset-y-0 left-0 z-40 flex w-64 flex-col border-r border-[var(--saic-border)] bg-[#fbf8ed]/90 shadow-[8px_0_30px_rgba(71,60,51,.04)] backdrop-blur-xl transition-transform duration-150 lg:static lg:translate-x-0 ${
            drawerOpen ? 'translate-x-0' : '-translate-x-full'
          }`}
        >
          <div className="flex h-16 items-center justify-between border-b border-[var(--saic-border)] px-5">
            <div>
              <div className="flex items-center gap-2.5">
                <span className="grid h-9 w-9 place-items-center rounded-xl bg-[#65783d] text-white shadow-sm"><GraduationCap className="h-5 w-5" aria-hidden="true" /></span>
                <div>
                  <p className="text-sm font-semibold tracking-tight text-slate-900">SAIC CAMPUS</p>
                  <p className="text-xs text-slate-500">Administration</p>
                </div>
              </div>
            </div>
            <button
              type="button"
              onClick={() => setDrawerOpen(false)}
              aria-label="Close navigation menu"
              className="rounded-md p-1.5 text-slate-600 hover:bg-slate-100 lg:hidden"
            >
              <X className="h-5 w-5" aria-hidden="true" />
            </button>
          </div>

          <nav aria-label="Admin navigation" className="flex-1 space-y-4 overflow-y-auto p-3">
            {sections.map((section) => {
              const items = NAV_ITEMS.filter(
                (item) =>
                  item.section === section.id &&
                  (!item.requiredPermission || hasPermission(item.requiredPermission)),
              );
              if (items.length === 0) return null;

              return (
                <div key={section.id} className="space-y-1">
                  <p className="px-3 text-[11px] font-semibold tracking-wider text-slate-400 uppercase">
                    {section.title}
                  </p>
                  {items.map((item) => {
                    const isCurrent =
                      item.href === '/' ? pathname === '/' : pathname.startsWith(item.href);

                    return (
                      <Link
                        key={item.label}
                        href={item.href}
                        onClick={() => setDrawerOpen(false)}
                        aria-current={isCurrent ? 'page' : undefined}
                        className={`flex items-center rounded-lg px-3 py-2 text-sm font-medium transition-colors ${
                          isCurrent
                            ? 'border-l-2 border-[#65783d] bg-[#e8eddc] text-[#473c33]'
                            : 'text-slate-700 hover:bg-slate-100 hover:text-slate-900'
                        }`}
                      >
                        <span className="flex items-center gap-2.5">
                          <NavIcon icon={item.icon} />
                          <span>{item.label}</span>
                        </span>
                      </Link>
                    );
                  })}
                </div>
              );
            })}
          </nav>

          <div className="border-t border-[var(--saic-border)] p-4 text-xs leading-5 text-slate-500">
            SAIC Institute of Management and Technology
          </div>
        </aside>

        <div className="flex min-w-0 flex-1 flex-col">
          <header className="sticky top-0 z-20 flex h-16 items-center justify-between border-b border-[var(--saic-border)] bg-[#fbf8ed]/85 px-4 backdrop-blur-xl sm:px-6">
            <div className="flex items-center gap-3">
              <button
                type="button"
                onClick={() => setDrawerOpen((open) => !open)}
                aria-label="Toggle navigation menu"
                aria-expanded={drawerOpen}
                className="rounded-md border border-slate-200 p-2 text-slate-700 hover:bg-slate-100 lg:hidden"
              >
                <Menu className="h-5 w-5" aria-hidden="true" />
              </button>
              <span className="inline-flex items-center rounded-full border border-slate-200 bg-slate-100 px-2.5 py-1 text-xs font-medium text-slate-700">
                SAIC Administration
              </span>
            </div>

            {authenticated ? (
              <div className="flex items-center gap-3">
                {user && (
                  <Link
                    href="/settings"
                    className="hidden items-center gap-2 rounded-lg border border-slate-200 bg-slate-50 px-2.5 py-1 text-xs text-slate-700 hover:bg-slate-100 sm:inline-flex"
                  >
                    <UserCircle2 className="h-4 w-4 text-slate-500" aria-hidden="true" />
                    <span className="font-medium text-slate-900">{user.fullName}</span>
                    <span className="text-slate-500">({user.roles.join(', ')})</span>
                  </Link>
                )}
                <button
                  type="button"
                  onClick={() => void handleLogout()}
                  className="inline-flex items-center gap-1.5 rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-sm font-medium text-slate-700 hover:bg-slate-50"
                >
                  <LogOut className="h-4 w-4" aria-hidden="true" />
                  <span>Sign Out</span>
                </button>
              </div>
            ) : (
              <Link
                href="/login"
                className="inline-flex items-center gap-1.5 rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-sm font-medium text-slate-700 hover:bg-slate-50"
              >
                <LogIn className="h-4 w-4" aria-hidden="true" />
                <span>Sign In</span>
              </Link>
            )}
          </header>

          <main className="flex-1 p-4 sm:p-6 lg:p-8">{children}</main>
        </div>
      </div>
    </AdminSessionContext.Provider>
  );
}
