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

const navItems = [
  { href: '/employee', icon: 'ri-dashboard-line', label: 'My Dashboard' },
  { href: '/employee/profile', icon: 'ri-user-line', label: 'My Profile' },
  { href: '/employee/leave', icon: 'ri-calendar-check-line', label: 'My Leave' },
  { href: '/employee/training', icon: 'ri-graduation-cap-line', label: 'Training & Development' },
  { href: '/employee/performance', icon: 'ri-bar-chart-line', label: 'Performance' },
];

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

function EmployeeSidebarContent({ onClose }: { onClose?: () => void }) {
  const { user } = useAuth();
  const pathname = usePathname();

  return (
    <div className="h-full w-64 flex flex-col" style={{ background: '#B22698' }}>
      <div className="flex flex-col items-center py-5 px-4 border-b border-white/20">
        <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">Employee 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.2)', border: '2px solid rgba(255,255,255,0.3)' }}>
            {user?.avatar}
          </div>
          <div className="min-w-0">
            <p className="text-white font-bold text-sm truncate">{user?.name}</p>
            <p className="text-pink-200 text-xs truncate">{user?.employeeId} · {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 font-medium">{item.label}</span>
            </Link>
          );
        })}
      </nav>
      <div className="p-4 border-t border-white/20">
        <div className="text-pink-200/60 text-xs text-center">
          Uwezo Fund HRMS v2.0
        </div>
      </div>
    </div>
  );
}

export default function EmployeeLayout({ children, title }: EmployeeLayoutProps) {
  const { user, isLoading } = useAuth();
  const router = useRouter();
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [mounted, setMounted] = useState(false);

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

  useEffect(() => {
    if (!mounted) return;
    let t: ReturnType<typeof setTimeout>;
    
    // Only redirect after loading is complete
    if (!isLoading) {
      // Check if user exists
      if (!user) {
        t = setTimeout(() => router.replace('/login'), 0);
      } 
      // Check if user role is allowed (employee, EMPLOYEE, intern, INTERN)
      else {
        const allowedRoles = ['employee', 'EMPLOYEE', 'intern', 'INTERN'];
        const userRole = user.role?.toLowerCase();
        const isIntern = user.isIntern === true;
        
        if (!allowedRoles.includes(userRole) && !isIntern) {
          t = setTimeout(() => router.replace('/login'), 0);
        }
      }
    }
    
    return () => clearTimeout(t);
  }, [user, isLoading, router, mounted]);

  // Show loading while checking auth
  if (!mounted || isLoading) {
    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: '#B22698' }}></i>
            </div>
            <p className="text-gray-400 text-sm">Loading portal...</p>
          </div>
        </div>
      </div>
    );
  }

  // Don't render if no user (will redirect)
  if (!user) {
    return null;
  }

  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">
        <EmployeeSidebarContent />
      </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">
            <EmployeeSidebarContent 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 transition-all flex-shrink-0"
        >
          <i className="ri-menu-line text-xl" style={{ color: '#B22698' }}></i>
        </button>
        <div className="flex-1 min-w-0">
          <p className="text-xs text-gray-400 hidden sm:block">Employee Portal</p>
          <h1 className="text-sm lg:text-base font-bold text-gray-800 truncate">{title}</h1>
        </div>
        <div className="flex items-center gap-2 flex-shrink-0">
          <NotificationBell />
          <ProfileDropdown />
        </div>
      </header>

      <main className="lg:ml-64 pt-16 flex-1">
        <div className="p-4 lg:p-6">{children}</div>
      </main>
      <div className="lg:ml-64">
        <EmployeeFooter />
      </div>
    </div>
  );
}
