/**
 * Dashboard Layout
 *
 * Layout with sidebar navigation for dashboard pages
 */

'use client';

import { useAuth } from '@/lib/context/auth-context';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { useState, useEffect } from 'react';
import NotificationDropdown from '@/components/NotificationDropdown';
import AdminPanelDropdown from '@/components/admin/AdminPanelDropdown';
import Image from 'next/image';
import {
  BarChart3,
  Package,
  FileText,
  Search,
  BookOpen,
  Building2,
  Users,
  LogOut,
  Lock,
  Key,
  Home,
  User,
} from 'lucide-react';
import { useSubscription } from '@/lib/context/subscription-context';
import StatusBadge from '@/components/ui/StatusBadge';
import type { PlanFeature } from '@/lib/api/subscriptions';

export default function DashboardLayout({ children }: { children: React.ReactNode }) {
  const { user, logout, loading, isAuthenticated } = useAuth();
  const { hasFeature, subscription } = useSubscription();
  const pathname = usePathname();
  const router = useRouter();
  const [sidebarOpen, setSidebarOpen] = useState(false);

  useEffect(() => {
    if (!loading && !isAuthenticated) {
      router.replace(`/login?redirect=${encodeURIComponent(pathname)}`);
    }
  }, [loading, isAuthenticated, router, pathname]);

  if (loading) {
    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>
    );
  }

  if (!isAuthenticated) {
    return null;
  }

  const navigation: Array<{ name: string; href: string; icon: any; requiredFeature?: PlanFeature }> = [
    { name: 'Tableau de bord', href: '/dashboard', icon: BarChart3, requiredFeature: 'dashboard' },
    { name: 'Réservations', href: '/dashboard/bookings', icon: Package },
    { name: 'Documents', href: '/dashboard/documents', icon: FileText },
    { name: 'Suivi', href: '/dashboard/track-trace', icon: Search, requiredFeature: 'dashboard' },
    { name: 'Wiki Maritime', href: '/dashboard/wiki', icon: BookOpen, requiredFeature: 'wiki' },
    { name: 'Organisation', href: '/dashboard/settings/organization', icon: Building2 },
    { name: 'Clés API', href: '/dashboard/settings/api-keys', icon: Key, requiredFeature: 'api_access' as PlanFeature },
    // ADMIN and MANAGER only navigation items
    ...(user?.role === 'ADMIN' || user?.role === 'MANAGER' ? [
      { name: 'Utilisateurs', href: '/dashboard/settings/users', icon: Users, requiredFeature: 'user_management' as PlanFeature },
    ] : []),
  ];

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

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

      {/* Sidebar */}
      <div
        className={`fixed inset-y-0 left-0 z-50 w-64 bg-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">
          {/* Logo */}
          <div className="flex items-center justify-between h-16 px-6 border-b">
            <Link href="/dashboard" className="text-2xl font-bold text-blue-600">
               <Image
                              src="/assets/logos/logo-black.svg"
                              alt="Xpeditis"
                              width={50}
                              height={60}
                              priority
                              className="h-auto"
                            />
            </Link>
            <button
              className="lg:hidden text-gray-500 hover:text-gray-700"
              onClick={() => setSidebarOpen(false)}
            >
              <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>

          {/* Navigation */}
          <nav className="flex-1 px-4 py-6 space-y-2 overflow-y-auto">
            {navigation.map(item => {
              const locked = item.requiredFeature && !hasFeature(item.requiredFeature);
              return (
                <Link
                  key={item.name}
                  href={locked ? '/pricing' : item.href}
                  className={`flex items-center px-4 py-3 text-sm font-medium rounded-lg transition-colors ${
                    locked
                      ? 'text-gray-400 hover:bg-gray-50'
                      : isActive(item.href)
                        ? 'bg-blue-50 text-blue-700'
                        : 'text-gray-700 hover:bg-gray-100'
                  }`}
                >
                  <item.icon className="mr-3 h-5 w-5" />
                  <span className="flex-1">{item.name}</span>
                  {locked && <Lock className="w-4 h-4 text-gray-300" />}
                </Link>
              );
            })}

            {/* Admin Panel - ADMIN role only */}
            {user?.role === 'ADMIN' && (
              <div className="pt-4 mt-4 border-t">
                <AdminPanelDropdown />
              </div>
            )}
          </nav>

          {/* User section */}
          <div className="border-t p-4">
            <div className="flex items-center space-x-3 mb-4">
              <div className="w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center text-white font-semibold">
                {user?.firstName?.[0]}
                {user?.lastName?.[0]}
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-1.5">
                  <p className="text-sm font-medium text-gray-900 truncate">
                    {user?.firstName} {user?.lastName}
                  </p>
                  {subscription?.planDetails?.statusBadge && subscription.planDetails.statusBadge !== 'none' && (
                    <StatusBadge badge={subscription.planDetails.statusBadge} size="sm" />
                  )}
                </div>
                <p className="text-xs text-gray-500 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-700 bg-red-50 rounded-lg hover:bg-red-100 transition-colors"
            >
              <LogOut className="w-4 h-4 mr-2" />
              Déconnexion
            </button>
          </div>
        </div>
      </div>

      {/* Main content */}
      <div className="lg:pl-64">
        {/* Top bar */}
        <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)}
          >
            <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>
          <div className="flex-1 lg:flex-none">
            <h1 className="text-base lg:text-xl font-semibold text-gray-900 ml-3 lg:ml-0">
              {navigation.find(item => isActive(item.href))?.name || 'Tableau de bord'}
            </h1>
          </div>
          <div className="flex items-center space-x-3 lg:space-x-4">
            {/* Notifications */}
            <NotificationDropdown />

            {/* User Initials */}
            <Link href="/dashboard/profile" className="w-8 h-8 lg:w-9 lg:h-9 bg-blue-600 rounded-full flex items-center justify-center text-white text-sm font-semibold hover:bg-blue-700 transition-colors">
              {user?.firstName?.[0]}{user?.lastName?.[0]}
            </Link>
          </div>
        </div>

        {/* Page content — extra bottom padding on mobile for bottom nav */}
        <main className="p-4 lg:p-6 pb-24 lg:pb-6">{children}</main>
      </div>

      {/* Mobile bottom navigation bar */}
      <nav className="fixed bottom-0 left-0 right-0 z-30 bg-white border-t border-gray-200 lg:hidden">
        <div className="grid grid-cols-5 h-16">
          {[
            { href: '/dashboard', icon: Home, label: 'Accueil' },
            { href: '/dashboard/bookings', icon: Package, label: 'Réservations' },
            { href: '/dashboard/documents', icon: FileText, label: 'Documents' },
            { href: '/dashboard/track-trace', icon: Search, label: 'Suivi' },
            { href: '/dashboard/profile', icon: User, label: 'Profil' },
          ].map((item) => {
            const active = item.href === '/dashboard' ? pathname === item.href : pathname.startsWith(item.href);
            return (
              <Link
                key={item.href}
                href={item.href}
                className={`flex flex-col items-center justify-center space-y-0.5 transition-colors ${
                  active ? 'text-blue-600' : 'text-gray-500 hover:text-gray-700'
                }`}
              >
                <item.icon className="w-5 h-5" />
                <span className="text-[10px] font-medium leading-tight">{item.label}</span>
              </Link>
            );
          })}
        </div>
      </nav>
    </div>
  );
}
