'use client';

import { usePathname, useRouter, useParams } from 'next/navigation';
import Link from 'next/link';
import { LogOut, Menu, X } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { useAuthStore } from '@/store/authStore';
import { useState, useEffect, useSyncExternalStore } from 'react';
import { api } from '@/lib/api';

export interface MenuItemGroup {
  title?: string;
  items: {
    href: string;
    label: string;
    icon: LucideIcon;
    exact?: boolean;
  }[];
}

interface DashboardLayoutProps {
  children: React.ReactNode;
  menuGroups: MenuItemGroup[];
  headerLogo?: React.ReactNode;
  requireRole?: string[];
  topNav?: React.ReactNode;
}

export default function DashboardLayout({
  children,
  menuGroups,
  headerLogo,
  requireRole,
  topNav
}: DashboardLayoutProps) {
  const pathname = usePathname();
  const router = useRouter();
  const routeParams = useParams();
  const locale = (routeParams?.locale as string) || 'vi';

  const user = useAuthStore(s => s.user);
  const token = useAuthStore(s => s.token);
  const logout = useAuthStore(s => s.logout);
  const mounted = useSyncExternalStore(() => () => undefined, () => true, () => false);
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [chatUnread, setChatUnread] = useState(0);

  useEffect(() => {
    if (mounted) {
      if (!token) {
        router.push(`/${locale}/auth/login`);
        return;
      }
      if (requireRole && requireRole.length > 0) {
        let actualRole = user?.role?.name || user?.role;
        if (!actualRole && token) {
          try {
            const base64Url = token.split('.')[1];
            const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
            const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join(''));
            const decoded = JSON.parse(jsonPayload);
            actualRole = decoded.role;
          } catch {}
        }

        if (!requireRole.includes(actualRole)) {
          router.push(`/${locale}`);
        }
      }
    }
  }, [mounted, token, user, router, locale, requireRole]);

  useEffect(() => {
    const role = user?.role?.name || user?.role;
    if (!token || !['ADMIN', 'SUPER_ADMIN'].includes(role)) return;
    const loadUnread = () => api.get('/chat/admin/unread-count').then((response) => setChatUnread(response.data.total || 0)).catch(() => undefined);
    void loadUnread();
    const interval = window.setInterval(loadUnread, 30000);
    return () => window.clearInterval(interval);
  }, [token, user]);

  if (!mounted || !token) {
    return <div className="min-h-screen bg-background flex items-center justify-center text-foreground">Checking permissions...</div>;
  }

  if (requireRole && requireRole.length > 0) {
    let actualRole = user?.role?.name || user?.role;
    if (!actualRole && token) {
      try {
        const base64Url = token.split('.')[1];
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join(''));
        actualRole = JSON.parse(jsonPayload).role;
      } catch {}
    }
    if (!requireRole.includes(actualRole)) {
      return <div className="min-h-screen bg-background flex items-center justify-center text-foreground">Checking permissions...</div>;
    }
  }

  const handleLogout = () => {
    logout();
    router.push(`/${locale}/auth/login`);
  };

  return (
    <div className="min-h-screen bg-background text-foreground flex flex-col md:flex-row overflow-hidden">

      {/* Mobile Topbar */}
      <div className="md:hidden flex items-center justify-between p-4 bg-sidebar border-b border-border">
        {headerLogo || <div className="font-bold">Dashboard</div>}
        <button onClick={() => setSidebarOpen(!sidebarOpen)} className="p-2 bg-muted rounded-lg">
          {sidebarOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
        </button>
      </div>

      {/* Sidebar */}
      <aside className={`
        fixed md:static inset-y-0 left-0 z-50
        w-64 bg-sidebar border-r border-border flex flex-col transition-transform duration-300
        ${sidebarOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0'}
      `}>
        {/* Sidebar Header */}
        <div className="hidden md:flex h-16 items-center px-6 border-b border-border">
          {headerLogo}
        </div>

        {/* Navigation */}
        <div className="flex-1 overflow-y-auto py-6 px-4 space-y-6">
          {menuGroups.map((group, idx) => (
            <div key={idx}>
              {group.title && (
                <h3 className="text-[10px] font-bold text-muted-foreground mb-2 tracking-wider uppercase px-2">
                  {group.title}
                </h3>
              )}
              <nav className="space-y-0.5">
                {group.items.map((item) => {
                  const fullHref = `/${locale}${item.href}`;
                  const isExact = item.exact;
                  const active = isExact
                    ? pathname === fullHref
                    : (pathname === fullHref || (item.href !== '/admin' && item.href !== '/seller/dashboard' && pathname.startsWith(fullHref)));

                  return (
                    <Link
                      key={item.href}
                      href={fullHref}
                      prefetch
                      onMouseEnter={() => router.prefetch(fullHref)}
                      onFocus={() => router.prefetch(fullHref)}
                      onClick={() => { setSidebarOpen(false); }}
                      className={`flex items-center gap-3 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
                        active
                          ? 'bg-primary/10 text-primary'
                          : 'text-muted-foreground hover:text-foreground hover:bg-muted'
                      }`}
                    >
                      <item.icon className="w-4 h-4 shrink-0" />
                      <span>{item.label}</span>{item.href === '/admin/chat-center' && chatUnread > 0 && <span className="ml-auto h-2.5 w-2.5 animate-pulse rounded-full bg-red-500 shadow-[0_0_8px_rgba(239,68,68,.8)]" />}
                    </Link>
                  );
                })}
              </nav>
            </div>
          ))}
        </div>

        {/* Logout */}
        <div className="p-4 border-t border-border">
          <button
            onClick={handleLogout}
            className="flex w-full items-center gap-3 px-3 py-2 rounded-lg text-sm font-medium text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
          >
            <LogOut className="w-4 h-4 shrink-0" />
            <span>Đăng xuất</span>
          </button>
        </div>
      </aside>

      {/* Main Content Area */}
      <main className="flex-1 flex flex-col min-w-0 h-screen overflow-hidden bg-background">
        {topNav}
        <div className="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8">
          <div className="max-w-7xl mx-auto w-full">
            {children}
          </div>
        </div>
      </main>

      {/* Mobile Overlay */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 bg-black/50 z-40 md:hidden"
          onClick={() => setSidebarOpen(false)}
        />
      )}
    </div>
  );
}
