'use client';

import { useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useAuth } from '@/lib/context/auth-context';
import { Link, usePathname, useRouter } from '@/i18n/navigation';
import LanguageSwitcher from '@/components/LanguageSwitcher';
import NotificationDropdown from '@/components/NotificationDropdown';
import Image from 'next/image';
import {
  Users,
  Building2,
  Package,
  FileText,
  BarChart3,
  Newspaper,
  ScrollText,
  ArrowLeft,
  LogOut,
  ShieldCheck,
  type LucideIcon,
} from 'lucide-react';

interface AdminNavItem {
  key: string;
  href: string;
  icon: LucideIcon;
}

const adminNavItems: AdminNavItem[] = [
  { key: 'users', href: '/admin/users', icon: Users },
  { key: 'organizations', href: '/admin/organizations', icon: Building2 },
  { key: 'bookings', href: '/admin/bookings', icon: Package },
  { key: 'documents', href: '/admin/documents', icon: FileText },
  { key: 'csvRates', href: '/admin/csv-rates', icon: BarChart3 },
  { key: 'blog', href: '/admin/blog', icon: Newspaper },
  { key: 'logs', href: '/admin/logs', icon: ScrollText },
];

export default function AdminLayout({ children }: { children: React.ReactNode }) {
  const { user, logout, loading, isAuthenticated } = useAuth();
  const pathname = usePathname();
  const router = useRouter();
  const tItems = useTranslations('components.adminPanelDropdown');
  const tAdmin = useTranslations('admin');
  const [sidebarOpen, setSidebarOpen] = useState(false);

  // The /admin/login page lives under this segment but must render without the
  // admin chrome and without triggering the role guard.
  const isLoginRoute = pathname === '/admin/login';

  useEffect(() => {
    if (isLoginRoute || loading) return;
    if (!isAuthenticated) {
      router.replace('/admin/login');
      return;
    }
    if (user && user.role !== 'ADMIN') {
      router.replace('/dashboard');
    }
  }, [isLoginRoute, loading, isAuthenticated, user, router]);

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

  const authorized = isAuthenticated && user?.role === 'ADMIN';

  if (loading || !authorized) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="w-8 h-8 border-4 border-brand-turquoise border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  const isActive = (href: string) => pathname === href || pathname.startsWith(href + '/');

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

      <div
        className={`fixed inset-y-0 left-0 z-50 w-64 bg-brand-navy text-white shadow-lg 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">
          <div className="flex items-center justify-between h-16 px-6 border-b border-white/10">
            <Link href="/admin" className="flex items-center gap-2">
              <Image
                src="/assets/logos/logo-white.svg"
                alt="Xpeditis"
                width={44}
                height={52}
                priority
                className="h-auto"
              />
            </Link>
            <button
              className="lg:hidden text-white/70 hover:text-white"
              onClick={() => setSidebarOpen(false)}
              aria-label="Close menu"
            >
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            </button>
          </div>

          <div className="flex items-center gap-2 px-6 py-4 text-xs font-semibold uppercase tracking-wider text-brand-turquoise">
            <ShieldCheck className="w-4 h-4" />
            {tAdmin('panelTitle')}
          </div>

          <nav className="flex-1 px-4 pb-6 space-y-1 overflow-y-auto">
            {adminNavItems.map(item => {
              const Icon = item.icon;
              return (
                <Link
                  key={item.key}
                  href={item.href}
                  onClick={() => setSidebarOpen(false)}
                  className={`flex items-center px-4 py-3 text-sm font-medium rounded-lg transition-colors ${
                    isActive(item.href)
                      ? 'bg-brand-turquoise text-brand-navy'
                      : 'text-white/80 hover:bg-white/10 hover:text-white'
                  }`}
                >
                  <Icon className="mr-3 h-5 w-5" />
                  <span className="flex-1">{tItems(`items.${item.key}` as any)}</span>
                </Link>
              );
            })}
          </nav>

          <div className="border-t border-white/10 p-4 space-y-3">
            <Link
              href="/dashboard"
              className="flex items-center px-4 py-2.5 text-sm font-medium text-white/80 rounded-lg hover:bg-white/10 hover:text-white transition-colors"
            >
              <ArrowLeft className="w-4 h-4 mr-2" />
              {tAdmin('backToApp')}
            </Link>

            <div className="flex items-center space-x-3 px-2">
              <div className="w-10 h-10 bg-brand-turquoise rounded-full flex items-center justify-center text-brand-navy font-semibold">
                {user?.firstName?.[0]}
                {user?.lastName?.[0]}
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium text-white truncate">
                  {user?.firstName} {user?.lastName}
                </p>
                <p className="text-xs text-white/60 truncate">{user?.email}</p>
              </div>
            </div>

            <button
              onClick={logout}
              className="w-full flex items-center justify-center px-4 py-2 text-sm font-medium text-red-200 bg-red-500/20 rounded-lg hover:bg-red-500/30 transition-colors"
            >
              <LogOut className="w-4 h-4 mr-2" />
              {tAdmin('logout')}
            </button>
          </div>
        </div>
      </div>

      <div className="lg:pl-64">
        <div className="sticky top-0 z-10 flex items-center justify-between h-14 lg:h-16 px-4 lg:px-6 bg-white border-b">
          <button
            className="lg:hidden text-gray-500 hover:text-gray-700 p-1"
            onClick={() => setSidebarOpen(true)}
            aria-label="Open menu"
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M4 6h16M4 12h16M4 18h16"
              />
            </svg>
          </button>
          <h1 className="text-base lg:text-xl font-semibold text-gray-900 ml-3 lg:ml-0">
            {adminNavItems.find(item => isActive(item.href))
              ? tItems(`items.${adminNavItems.find(item => isActive(item.href))!.key}` as any)
              : tAdmin('title')}
          </h1>
          <div className="flex items-center space-x-3 lg:space-x-4">
            <LanguageSwitcher variant="light" />
            <NotificationDropdown />
          </div>
        </div>

        <main className="p-4 lg:p-6">{children}</main>
      </div>
    </div>
  );
}
