'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useRouter, usePathname, useSearchParams } from 'next/navigation';
import {
  LayoutDashboard, Building2, Users, MessageSquare, TrendingUp,
  Settings, Bell, LogOut, Menu, X, ChevronRight,
} from 'lucide-react';
import { useAuth } from '@/contexts/auth-context';

interface NavItem {
  label: string;
  href: string;
  icon: React.ReactNode;
}

interface DashboardShellProps {
  children: React.ReactNode;
  navItems: NavItem[];
  role: string;
  roleLabel: string;
  accentColor?: string;
}

export function DashboardShell({
  children,
  navItems,
  role,
  roleLabel,
  accentColor = '#C5A880',
}: DashboardShellProps) {
  const { user, logout } = useAuth();
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const [sidebarOpen, setSidebarOpen] = useState(false);

  const handleLogout = async () => {
    await logout();
    router.push('/login');
  };

  const initials = user
    ? `${user.first_name?.[0] ?? ''}${user.last_name?.[0] ?? ''}`.toUpperCase()
    : '??';

  return (
    <div className="flex h-screen overflow-hidden bg-[#f7f9fb] font-sans">
      {/* ── Sidebar ─────────────────────────────────────────── */}
      <aside
        className={`bg-[#0d1c32] h-full flex flex-col py-8 px-4 z-50 transition-all duration-300
          ${sidebarOpen ? 'w-64 fixed inset-y-0 left-0 shadow-2xl' : 'w-64 hidden lg:flex'}`}
      >
        {/* Logo */}
        <div className="mb-10 px-3 flex items-center justify-between">
          <div>
            <Link href="/">
              <h1 className="font-serif text-2xl font-bold text-white tracking-wide">Wild Dubai</h1>
            </Link>
            <p className="text-[10px] font-bold uppercase tracking-[0.25em] mt-0.5" style={{ color: accentColor }}>
              {roleLabel}
            </p>
          </div>
          <button
            onClick={() => setSidebarOpen(false)}
            className="lg:hidden text-white/40 hover:text-white"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Nav */}
        <nav className="flex-grow space-y-1">
          {navItems.map((item, index) => {
            const [itemPath, itemQuery] = item.href.split('?');
            const params = new URLSearchParams(itemQuery ?? '');
            const itemTab = params.get('tab');
            const currentTab = searchParams.get('tab');
            const isActive = pathname === itemPath && (itemTab ? currentTab === itemTab : !currentTab);

            return (
              <Link
                key={`${item.href}-${index}`}
                href={item.href}
                onClick={(e) => {
                  setSidebarOpen(false);
                  if (item.href === '#') {
                    e.preventDefault();
                  }
                }}
                className={`flex items-center gap-3.5 p-3.5 rounded-lg transition-all text-[11px] font-bold tracking-[0.1em] uppercase ${
                  isActive
                    ? 'text-[#0d1c32] shadow-md'
                    : 'text-white/60 hover:text-white hover:bg-white/5'
                }`}
                style={isActive ? { backgroundColor: accentColor } : {}}
              >
                <span className="w-4 h-4 shrink-0">{item.icon}</span>
                {item.label}
              </Link>
            );
          })}
        </nav>

        {/* User card */}
        <div className="mt-auto border-t border-white/10 pt-6 px-3">
          <div className="flex items-center gap-3 mb-4">
            <div
              className="w-10 h-10 rounded-full flex items-center justify-center font-bold text-sm text-[#0d1c32] shrink-0"
              style={{ backgroundColor: accentColor }}
            >
              {initials}
            </div>
            <div className="min-w-0">
              <p className="text-white font-bold text-sm truncate">
                {user?.first_name} {user?.last_name}
              </p>
              <p className="text-white/40 text-[9px] uppercase tracking-wider font-semibold truncate">
                {user?.email}
              </p>
            </div>
          </div>
          <button
            onClick={handleLogout}
            className="w-full flex items-center gap-2 text-white/50 hover:text-red-400 text-[10px] font-bold uppercase tracking-wider transition-colors py-2"
          >
            <LogOut className="w-3.5 h-3.5" />
            Sign Out
          </button>
        </div>
      </aside>

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

      {/* ── Main ────────────────────────────────────────────── */}
      <main className="flex-grow overflow-y-auto flex flex-col min-w-0">
        {/* Top bar */}
        <header className="h-16 px-6 lg:px-10 flex items-center justify-between sticky top-0 bg-[#f7f9fb]/95 backdrop-blur-md z-30 border-b border-gray-100 shrink-0">
          <button
            onClick={() => setSidebarOpen(true)}
            className="lg:hidden p-2 text-gray-500 hover:text-[#0d1c32] rounded-lg hover:bg-gray-100 transition-colors"
          >
            <Menu className="w-5 h-5" />
          </button>

          <div className="flex items-center gap-2 text-xs text-gray-400 font-medium">
            <Link href="/" className="hover:text-[#0d1c32] transition-colors">Home</Link>
            <ChevronRight className="w-3 h-3" />
            <span className="text-[#0d1c32] font-semibold capitalize">{roleLabel}</span>
          </div>

          <div className="flex items-center gap-3">
            <button className="relative p-2 hover:bg-gray-100 rounded-full transition-colors">
              <Bell className="w-4 h-4 text-gray-500" />
              <span className="absolute top-1.5 right-1.5 w-1.5 h-1.5 bg-red-500 rounded-full" />
            </button>
            <div
              className="w-8 h-8 rounded-full flex items-center justify-center font-bold text-xs text-[#0d1c32]"
              style={{ backgroundColor: accentColor }}
            >
              {initials}
            </div>
          </div>
        </header>

        {/* Page content */}
        <div className="flex-grow">{children}</div>
      </main>
    </div>
  );
}
