'use client';
import { useState, useEffect } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { useAuth } from '../lib/authContext';
import { useLeaveStore } from '../lib/leaveStore';
import Image from 'next/image';
import NotificationBell from '../lib/notificationBell';
import ProfileDropdown from './ProfileDropdown';

const navItems = [
  { href: '/hod', icon: 'ri-dashboard-line', label: 'Dashboard' },
  { href: '/hod/requests', icon: 'ri-file-list-3-line', label: 'Staff Leave Requests' },
  { href: '/hod/own-leave', icon: 'ri-calendar-check-line', label: 'My Leave' },
  { href: '/hod/department', icon: 'ri-team-line', label: 'My Department' },
  { href: '/hod/performance', icon: 'ri-bar-chart-line', label: 'Performance' },
  { href: '/hod/training', icon: 'ri-graduation-cap-line', label: 'Training & Development' },
  { href: '/hod/history', icon: 'ri-history-line', label: 'Approval History' },
];

const THEME = '#B22698';

interface HODLayoutProps {
  children: React.ReactNode;
  title: string;
}

export default function HODLayout({ children, title }: HODLayoutProps) {
  const { user, isLoading } = useAuth();
  const { requests } = useLeaveStore();
  const router = useRouter();
  const pathname = usePathname();
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!mounted) return;
    let t: ReturnType<typeof setTimeout>;
    if (!isLoading && !user) {
      t = setTimeout(() => router.replace('/login'), 0);
    } else if (!isLoading && user && user.role !== 'hod') {
      t = setTimeout(() => router.replace('/login'), 0);
    }
    return () => clearTimeout(t);
  }, [user, isLoading, router, mounted]);

  if (!mounted || isLoading || !user) {
    return (
      <div className="min-h-screen bg-gray-50 flex flex-col">
        <div className="flex-1 flex items-center justify-center">
          <div className="text-center">
            <div className="w-10 h-10 flex items-center justify-center mx-auto mb-3">
              <i className="ri-loader-4-line text-4xl animate-spin" style={{ color: THEME }}></i>
            </div>
            <p className="text-gray-400 text-sm">Loading portal...</p>
          </div>
        </div>
      </div>
    );
  }

  const pendingCount = requests.filter(r => r.dept === user.dept && r.status === 'Pending').length;

  const SidebarContent = ({ onClose }: { onClose?: () => void }) => (
    <aside className="h-full w-64 flex flex-col" style={{ background: THEME }}>
      <div className="flex flex-col items-center py-5 px-4 border-b border-white/10">
        <Image src="https://static.readdy.ai/image/724ebe353b2be7ddbcbd1af9bf145acb/1129a928a47473f2ca8ce9477fd8f692.png" alt="Uwezo Fund" width={52} height={52} className="rounded-full mb-2 bg-white p-1 shadow-lg" />
        <span className="text-white font-bold text-sm">Uwezo Fund</span>
        <span className="text-pink-200 text-xs mt-0.5">HOD Portal</span>
      </div>
      <div className="px-4 py-3 border-b border-white/10 bg-white/5">
        <div className="flex items-center gap-2">
          <div className="w-9 h-9 rounded-full flex items-center justify-center text-white font-bold text-sm flex-shrink-0" style={{ background: 'rgba(255,255,255,0.15)', border: '2px solid rgba(255,255,255,0.25)' }}>
            {user.avatar}
          </div>
          <div className="min-w-0">
            <p className="text-white text-sm font-semibold truncate">{user.name}</p>
            <p className="text-pink-200 text-xs truncate">{user.dept}</p>
          </div>
        </div>
      </div>
      <nav className="flex-1 overflow-y-auto py-3 px-3">
        {navItems.map(item => {
          const active = pathname === item.href;
          return (
            <Link key={item.href} href={item.href} onClick={onClose}
              className={`flex items-center gap-3 px-3 py-2.5 rounded-lg mb-0.5 transition-all cursor-pointer whitespace-nowrap ${active ? 'bg-white/25 text-white font-semibold border-l-[3px] border-yellow-300 pl-2.5' : 'text-pink-100 hover:bg-white/15 hover:text-white'}`}>
              <div className="w-5 h-5 flex items-center justify-center"><i className={`${item.icon} text-lg`}></i></div>
              <span className="text-sm">{item.label}</span>
            </Link>
          );
        })}
      </nav>
      <div className="p-4 border-t border-white/10">
        <Link href="/profile" className="flex items-center gap-2 text-pink-100 hover:text-white cursor-pointer w-full px-3 py-2 rounded-lg hover:bg-white/10 transition-all">
          <div className="w-5 h-5 flex items-center justify-center"><i className="ri-user-line text-lg"></i></div>
          <span className="text-sm">My Profile</span>
        </Link>
      </div>
    </aside>
  );

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">
      <div className="hidden lg:block fixed left-0 top-0 h-screen w-64 z-40"><SidebarContent /></div>
      {sidebarOpen && (
        <div className="lg:hidden fixed inset-0 z-50 flex">
          <div className="fixed inset-0 bg-black/50" onClick={() => setSidebarOpen(false)}></div>
          <div className="relative w-64 h-full shadow-2xl"><SidebarContent onClose={() => setSidebarOpen(false)} /></div>
        </div>
      )}
      <header className="fixed top-0 left-0 lg:left-64 right-0 h-16 bg-white border-b border-gray-100 flex items-center px-4 lg:px-6 z-30 shadow-sm gap-3">
        <button onClick={() => setSidebarOpen(true)} className="lg:hidden w-9 h-9 flex items-center justify-center rounded-lg hover:bg-gray-100 cursor-pointer">
          <i className="ri-menu-line text-xl" style={{ color: THEME }}></i>
        </button>
        <div className="flex-1 min-w-0">
          <p className="text-xs text-gray-400">HOD Portal — {user.dept}</p>
          <h1 className="text-sm lg:text-base font-bold text-gray-800 truncate">{title}</h1>
        </div>
        <div className="flex items-center gap-2">
          <NotificationBell />
          <ProfileDropdown />
        </div>
      </header>
      <main className="lg:ml-64 pt-16 flex-1">
        <div className="p-4 lg:p-6">{children}</div>
      </main>
    </div>
  );
}