'use client';
import { useSession, signOut } from 'next-auth/react';
import { useRouter, usePathname } from 'next/navigation';
import { useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { LayoutDashboard, Truck, FolderOpen, Users, BarChart3, LogOut, Menu, X, Activity } from 'lucide-react';
import { useState } from 'react';
import { useLanguage } from '@/lib/i18n/language-context';
import { LanguageSwitcher } from '@/components/public/language-switcher';

export default function AdminDashboardLayout({ children }: { children: React.ReactNode }) {
  const { data: session, status } = useSession() || {};
  const router = useRouter();
  const pathname = usePathname();
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const { t, locale } = useLanguage();

  const sidebarLinks = [
    { href: '/admin/dashboard', label: t.admin.sidebar.dashboard, icon: LayoutDashboard },
    { href: '/admin/vehicles', label: t.admin.sidebar.vehicles, icon: Truck },
    { href: '/admin/categories', label: t.admin.sidebar.categories, icon: FolderOpen },
    { href: '/admin/leads', label: t.admin.sidebar.leads, icon: Users },
    { href: '/admin/reports', label: t.admin.sidebar.reports, icon: BarChart3 },
    { href: '/admin/analytics', label: locale === 'es' ? 'Analíticas' : 'Analytics', icon: Activity },
  ];

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.replace('/admin/login');
    }
  }, [status, router]);

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

  if (!session) return null;

  return (
    <div className="min-h-screen bg-gray-50 flex">
      {/* Sidebar */}
      <aside className={`fixed inset-y-0 left-0 z-40 w-64 bg-[#1a1a1a] text-white transform transition-transform lg:translate-x-0 ${sidebarOpen ? 'translate-x-0' : '-translate-x-full'}`}>
        <div className="p-4 border-b border-gray-800">
          <div className="relative w-[150px] h-[40px]">
            <Image src="/images/logo.png" alt="Logo" fill className="object-contain brightness-200" />
          </div>
        </div>
        <nav className="p-4 space-y-1">
          {(sidebarLinks ?? [])?.map((link: any) => {
            const isActive = pathname?.startsWith(link?.href);
            return (
              <Link key={link?.href} href={link?.href} onClick={() => setSidebarOpen(false)} className={`flex items-center gap-3 px-4 py-3 rounded-lg text-sm font-medium transition ${isActive ? 'bg-red-600 text-white' : 'text-gray-400 hover:text-white hover:bg-white/5'}`}>
                <link.icon className="w-5 h-5" />
                {link?.label}
              </Link>
            );
          })}
        </nav>
        <div className="absolute bottom-4 left-4 right-4">
          <div className="px-4 mb-3">
            <LanguageSwitcher variant="admin" />
          </div>
          <div className="text-xs text-gray-500 mb-2 px-4 truncate">{session?.user?.email ?? ''}</div>
          <button onClick={() => signOut({ callbackUrl: '/admin/login' })} className="flex items-center gap-3 px-4 py-3 rounded-lg text-sm text-gray-400 hover:text-white hover:bg-white/5 transition w-full">
            <LogOut className="w-5 h-5" /> {t.admin.sidebar.logout}
          </button>
          <Link href="/" className="flex items-center gap-3 px-4 py-2 rounded-lg text-xs text-gray-500 hover:text-gray-300 transition mt-1">
            {t.admin.sidebar.viewSite} &rarr;
          </Link>
        </div>
      </aside>

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

      {/* Main */}
      <div className="flex-1 lg:ml-64">
        <header className="bg-white border-b border-gray-200 px-4 py-3 flex items-center justify-between sticky top-0 z-20">
          <button onClick={() => setSidebarOpen(!sidebarOpen)} className="lg:hidden p-2 text-gray-600">
            {sidebarOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
          </button>
          <div className="text-sm text-gray-500 hidden lg:block">{t.admin.sidebar.adminPanel}</div>
          <div className="text-sm text-gray-500">{session?.user?.name ?? session?.user?.email ?? ''}</div>
        </header>
        <main className="p-4 lg:p-6">{children}</main>
      </div>
    </div>
  );
}
