'use client';

import { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { usePathname, useRouter } from 'next/navigation';
import {
  LayoutDashboard,
  Package,
  ShoppingCart,
  FolderTree,
  Settings,
  Menu,
  X,
  LogOut,
  User,
  Ruler,
  Palette,
  Truck,
  Globe,
  BookOpen,
} from 'lucide-react';
import { useSettings } from '../context/SettingsContext';
import { isMockEnabled } from '@/lib/mock/mock-mode';

export default function AdminLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [isCheckingAuth, setIsCheckingAuth] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [adminEmail, setAdminEmail] = useState<string | null>(null);
  const [adminName, setAdminName] = useState<string | null>(null);
  const pathname = usePathname();
  const router = useRouter();
  const { siteName } = useSettings();

  const isLoginPage = pathname === '/admin/login';

  const menuItems = useMemo(
    () => [
      { name: 'Dashboard', href: '/admin', icon: LayoutDashboard },
      { name: 'Products', href: '/admin/products', icon: Package },
      { name: 'Catalog', href: '/admin/catalog', icon: BookOpen },
      { name: 'Orders', href: '/admin/orders', icon: ShoppingCart },
      { name: 'Categories', href: '/admin/categories', icon: FolderTree },
      { name: 'Sizes', href: '/admin/sizes', icon: Ruler },
      { name: 'Colors', href: '/admin/colors', icon: Palette },
      { name: 'Shipping Methods', href: '/admin/shipping-methods', icon: Truck },
      { name: 'Countries', href: '/admin/countries', icon: Globe },
      { name: 'Settings', href: '/admin/settings', icon: Settings },
    ],
    []
  );

  useEffect(() => {
    if (isLoginPage) {
      setIsCheckingAuth(false);
      setIsAuthenticated(false);
      return;
    }

    let isMounted = true;

    const checkAuth = async () => {
      try {
        if (isMockEnabled()) {
          if (!isMounted) return;
          setIsAuthenticated(true);
          setAdminEmail('mock-admin@bakhtapparel.com');
          setAdminName('Mock Admin');
          return;
        }

        const response = await fetch('/api/admin/me', {
          credentials: 'include',
        });

        if (!isMounted) {
          return;
        }

        if (!response.ok) {
          setIsAuthenticated(false);
          setAdminEmail(null);
          setAdminName(null);
          router.replace('/admin/login');
          return;
        }

        const data = await response.json();
        setIsAuthenticated(true);
        setAdminEmail(data.email ?? null);
        setAdminName(
          [data.firstName, data.lastName].filter(Boolean).join(' ') || data.email || 'Admin User'
        );
      } catch (error) {
        console.error(error);
        if (isMounted) {
          setIsAuthenticated(false);
          setAdminEmail(null);
          setAdminName(null);
          router.replace('/admin/login');
        }
      } finally {
        if (isMounted) {
          setIsCheckingAuth(false);
        }
      }
    };

    void checkAuth();

    return () => {
      isMounted = false;
    };
  }, [isLoginPage, router, pathname]);

  const isActive = (href: string) => {
    if (href === '/admin') {
      return pathname === '/admin';
    }
    return pathname?.startsWith(href);
  };

  const handleLogout = async () => {
    try {
      if (isMockEnabled()) {
        return;
      }
      await fetch('/api/admin/logout', {
        method: 'POST',
        credentials: 'include',
      });
    } catch (error) {
      console.error(error);
    } finally {
      setIsAuthenticated(false);
      setAdminEmail(null);
      setAdminName(null);
      router.replace('/admin/login');
    }
  };

  if (isLoginPage) {
    return <>{children}</>;
  }

  if (isCheckingAuth) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 text-gray-600">
        <div className="text-sm">Checking permissions…</div>
      </div>
    );
  }

  if (!isAuthenticated) {
    return null;
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Mobile Sidebar Overlay */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 bg-black/50 z-40 lg:hidden"
          onClick={() => setSidebarOpen(false)}
        />
      )}

      {/* Sidebar */}
      <aside
        className={`fixed top-0 left-0 h-full w-64 bg-white border-r border-gray-200 z-50 transform transition-transform duration-300 ease-in-out lg:translate-x-0 ${
          sidebarOpen ? 'translate-x-0' : '-translate-x-full'
        }`}
      >
        <div className="flex flex-col h-full">
          {/* Logo */}
          <div className="flex items-center justify-between p-6 border-b border-gray-200">
            <Link href="/admin" className="flex items-center gap-3">
              <div className="relative h-10 w-36">
                <Image
                  src="/assets/logos/Untitled-1-02.png"
                  alt={`${siteName} Admin`}
                  fill
                  className="object-contain"
                  priority
                  unoptimized
                />
              </div>
            </Link>
            <button
              onClick={() => setSidebarOpen(false)}
              className="lg:hidden p-2 hover:bg-gray-100 rounded"
            >
              <X className="w-5 h-5" />
            </button>
          </div>

          {/* Navigation */}
          <nav className="flex-1 p-4 space-y-2 overflow-y-auto">
            {menuItems.map((item) => {
              const Icon = item.icon;
              const active = isActive(item.href);
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  onClick={() => setSidebarOpen(false)}
                  className={`flex items-center gap-3 px-4 py-3 rounded-lg transition-colors ${
                    active
                      ? 'bg-gray-900 text-white'
                      : 'text-gray-700 hover:bg-gray-100'
                  }`}
                >
                  <Icon className="w-5 h-5" />
                  <span className="font-medium">{item.name}</span>
                </Link>
              );
            })}
          </nav>

          {/* User Section */}
          <div className="p-4 border-t border-gray-200">
            <div className="flex items-center gap-3 px-4 py-3 text-gray-700">
              <div className="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center">
                <User className="w-5 h-5" />
              </div>
              <div className="flex-1">
                <p className="text-sm font-medium">{adminName ?? adminEmail ?? 'Admin User'}</p>
                <p className="text-xs text-gray-500">{adminEmail ?? 'No email on file'}</p>
              </div>
            </div>
            <button
              type="button"
              onClick={handleLogout}
              className="flex w-full items-center gap-3 px-4 py-3 rounded-lg text-gray-700 hover:bg-gray-100 transition-colors"
            >
              <LogOut className="w-5 h-5" />
              <span className="font-medium">Logout</span>
            </button>
          </div>
        </div>
      </aside>

      {/* Main Content */}
      <div className="lg:pl-64">
        {/* Top Bar */}
        <header className="sticky top-0 z-30 bg-white border-b border-gray-200">
          <div className="flex items-center justify-between px-6 py-4">
            <button
              onClick={() => setSidebarOpen(true)}
              className="lg:hidden p-2 hover:bg-gray-100 rounded"
            >
              <Menu className="w-6 h-6" />
            </button>
            <div className="flex items-center gap-4">
              <Link
                href="/"
                className="text-sm text-gray-600 hover:text-gray-900"
              >
                View Site
              </Link>
            </div>
          </div>
        </header>

        {/* Page Content */}
        <main className="p-6">{children}</main>
      </div>
    </div>
  );
}

