'use client';

import { useAuth } from '@/lib/context/auth-context';
import { Link, usePathname, useRouter } from '@/i18n/navigation';
import { useState, useEffect } from 'react';
import { useTranslations } from 'next-intl';
import NotificationDropdown from '@/components/NotificationDropdown';
import LanguageSwitcher from '@/components/LanguageSwitcher';
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 t = useTranslations('dashboard');
  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: t('nav.dashboard'), href: '/dashboard', icon: BarChart3, requiredFeature: 'dashboard' },
    { name: t('nav.bookings'), href: '/dashboard/bookings', icon: Package },
    { name: t('nav.documents'), href: '/dashboard/documents', icon: FileText },
    {
      name: t('nav.tracking'),
      href: '/dashboard/track-trace',
      icon: Search,
      requiredFeature: 'dashboard',
    },
    { name: t('nav.wiki'), href: '/dashboard/wiki', icon: BookOpen, requiredFeature: 'wiki' },
    { name: t('nav.organization'), href: '/dashboard/settings/organization', icon: Building2 },
    {
      name: t('nav.apiKeys'),
      href: '/dashboard/settings/api-keys',
      icon: Key,
      requiredFeature: 'api_access' as PlanFeature,
    },
    ...(user?.role === 'ADMIN' || user?.role === 'MANAGER'
      ? [
          {
            name: t('nav.users'),
            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">
      {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-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">
            <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>

          <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>
              );
            })}

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

          <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" />
              {t('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)}
          >
            <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 || t('topbar.defaultTitle')}
            </h1>
          </div>
          <div className="flex items-center space-x-3 lg:space-x-4">
            <LanguageSwitcher variant="light" />
            <NotificationDropdown />

            <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>

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

      <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: t('bottomNav.home') },
            { href: '/dashboard/bookings', icon: Package, label: t('bottomNav.bookings') },
            { href: '/dashboard/documents', icon: FileText, label: t('bottomNav.documents') },
            { href: '/dashboard/track-trace', icon: Search, label: t('bottomNav.tracking') },
            { href: '/dashboard/profile', icon: User, label: t('bottomNav.profile') },
          ].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>
  );
}
