'use client';

import { useState, type ReactNode } from 'react';
import { signOut } from 'next-auth/react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import ControlHorarioWidget from './control-horario-widget';
import {
  Shield, LayoutDashboard, Users, Mail, User, LogOut,
  Menu, X, ChevronRight, ClipboardList, Building2, CalendarDays, Settings, Wrench, FileText, BarChart, HelpCircle, Receipt
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

interface Props {
  children: ReactNode;
  userName: string;
  userEmail: string;
  userRole: string;
}

const adminNav = [
  { href: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
  { href: '/dashboard/avisos', label: 'Avisos', icon: ClipboardList },
  { href: '/dashboard/agenda', label: 'Agenda', icon: CalendarDays },
  { href: '/dashboard/partes', label: 'Partes de Trabajo', icon: Wrench },
  { href: '/dashboard/presupuestos', label: 'Presupuestos', icon: FileText },
  { href: '/dashboard/facturas', label: 'Facturación', icon: Receipt },
  { href: '/dashboard/clientes', label: 'Clientes', icon: Building2 },
  { href: '/dashboard/estadisticas', label: 'Estadísticas', icon: BarChart },
  { href: '/dashboard/configuracion', label: 'Configuración', icon: Settings },
  { href: '/dashboard/manual', label: 'Manual / Ayuda', icon: HelpCircle },
];

const operarioNav = [
  { href: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
  { href: '/dashboard/avisos', label: 'Avisos', icon: ClipboardList },
  { href: '/dashboard/agenda', label: 'Agenda', icon: CalendarDays },
  { href: '/dashboard/partes', label: 'Partes de Trabajo', icon: Wrench },
  { href: '/dashboard/presupuestos', label: 'Presupuestos', icon: FileText },
  { href: '/dashboard/clientes', label: 'Clientes', icon: Building2 },
];

export default function DashboardShell({ children, userName, userEmail, userRole }: Props) {
  const pathname = usePathname() ?? '/dashboard';
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const navItems = userRole === 'admin' ? adminNav : operarioNav;

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

  return (
    <div className="min-h-screen bg-[#f7fafc] flex">
      {/* Mobile overlay */}
      <AnimatePresence>
        {sidebarOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 0.5 }}
            exit={{ opacity: 0 }}
            onClick={() => setSidebarOpen(false)}
            className="fixed inset-0 bg-black z-30 lg:hidden"
          />
        )}
      </AnimatePresence>

      {/* Sidebar */}
      <aside className={`fixed inset-y-0 left-0 z-40 w-64 bg-[#1a365d] text-white transform transition-transform lg:translate-x-0 ${sidebarOpen ? 'translate-x-0' : '-translate-x-full'} flex flex-col shadow-xl`}>
        <div className="p-6 flex items-center justify-center border-b border-white/10 relative">
          <motion.div
            whileHover={{ scale: 1.02 }}
            className="bg-white p-3 rounded-xl w-full shadow-[0_10px_20px_rgba(0,0,0,0.3),0_6px_6px_rgba(0,0,0,0.2)] border border-white/20 transform -rotate-1"
          >
            <img src="/logo.png" alt="Climasan Blázquez S.L. Logo" className="w-full h-auto object-contain drop-shadow-md" />
          </motion.div>
          <button onClick={() => setSidebarOpen(false)} className="lg:hidden ml-auto p-1 hover:bg-white/10 rounded absolute right-4 top-4">
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="flex-1 overflow-y-auto custom-scrollbar">
          <nav className="p-3 space-y-1 mt-2">
            {navItems?.map((item) => {
              const Icon = item?.icon;
              const active = isActive(item?.href);
              return (
                <Link
                  key={item?.href}
                  href={item?.href}
                  onClick={() => setSidebarOpen(false)}
                  className={`flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all ${active
                    ? 'bg-white/15 text-white shadow-inner'
                    : 'text-white/70 hover:bg-white/10 hover:text-white'
                    }`}
                >
                  <Icon className="w-4 h-4 flex-shrink-0" />
                  <span>{item?.label}</span>
                  {active && <ChevronRight className="w-3 h-3 ml-auto" />}
                </Link>
              );
            })}
          </nav>

          {/* User info and secondary actions */}
          <div className="p-3 mt-4 border-t border-white/5">
            <p className="text-[10px] font-bold text-white/40 uppercase tracking-widest px-3 mb-2">Usuario</p>
            <Link
              href="/dashboard/profile"
              onClick={() => setSidebarOpen(false)}
              className={`flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all ${isActive('/dashboard/profile') ? 'bg-white/15 text-white' : 'text-white/70 hover:bg-white/10 hover:text-white'}`}
            >
              <User className="w-4 h-4 flex-shrink-0" />
              <span>Mi Perfil</span>
            </Link>
            <button
              onClick={() => signOut({ callbackUrl: '/login' })}
              className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium text-red-300 hover:bg-red-500/10 hover:text-red-200 transition-all mt-1"
            >
              <LogOut className="w-4 h-4 flex-shrink-0" />
              <span>Cerrar sesión</span>
            </button>
          </div>
        </div>

        {/* Footer info */}
        <div className="p-4 bg-black/10 flex items-center gap-3">
          <div className="w-8 h-8 rounded-full bg-[#3182ce] flex items-center justify-center text-xs font-bold shadow-lg">
            {userName?.charAt(0)?.toUpperCase?.() ?? 'U'}
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex justify-between items-center gap-2">
              <p className="text-xs font-semibold truncate">{userName}</p>
              <span className="text-[9px] px-1.5 py-0.5 rounded font-medium bg-white/20 text-white capitalize flex-shrink-0">
                {userRole}
              </span>
            </div>
            <p className="text-[10px] text-white/40 truncate">{userEmail}</p>
          </div>
        </div>
      </aside>

      {/* Main content */}
      <div className="flex-1 flex flex-col min-h-screen lg:ml-64">
        {/* Top bar */}
        <header className="bg-white border-b border-gray-200 px-4 py-3 flex items-center justify-between sticky top-0 z-20">
          <div className="flex items-center">
            <button
              onClick={() => setSidebarOpen(true)}
              className="lg:hidden p-2 hover:bg-gray-100 rounded-lg mr-3"
            >
              <Menu className="w-5 h-5 text-gray-600" />
            </button>
          </div>

          <div className="flex justify-end overflow-x-auto custom-scrollbar pb-1 -mb-1">
            <ControlHorarioWidget />
          </div>
        </header>

        <main className="flex-1 p-4 lg:p-6 max-w-7xl w-full mx-auto">
          {children}
        </main>
      </div>
    </div>
  );
}
