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

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

const THEME = '#B22698';

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

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

  const getInitials = (name: string) => {
    if (!name) return 'IN';
    return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2);
  };

  return (
    <div 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/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">Intern 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)' }}>
            {getInitials(user?.name || 'Intern')}
          </div>
          <div className="min-w-0">
            <p className="text-white font-bold text-sm truncate">{user?.name || 'Intern'}</p>
            <p className="text-pink-200 text-xs truncate">{user?.employeeId || 'INT001'} · Intern</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 InternLayout({ children, title }: InternLayoutProps) {
  const { user, isLoading } = useAuth();
  const router = useRouter();
  const [sidebarOpen, setSidebarOpen] = useState(false);

  // CRITICAL: Check authentication and role
  useEffect(() => {
    if (!isLoading) {
      if (!user) {
        console.log('InternLayout: No user found, redirecting to login');
        router.replace('/login');
      } else {
        const userRole = user.role?.toLowerCase();
        const isValidIntern = userRole === 'intern' || user.isIntern === true;
        
        if (!isValidIntern) {
          console.log('InternLayout: User is not an intern, role:', user.role, 'redirecting to login');
          router.replace('/login');
        } else {
          console.log('InternLayout: Intern authenticated:', user.email);
        }
      }
    }
  }, [user, isLoading, router]);

  // Show loading state while checking authentication
  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600 mx-auto"></div>
          <p className="text-gray-400 text-sm mt-2">Loading...</p>
        </div>
      </div>
    );
  }

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

  // Double-check role before rendering
  const userRole = user.role?.toLowerCase();
  if (userRole !== 'intern' && !user.isIntern) {
    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">
        <InternSidebarContent />
      </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">
            <InternSidebarContent 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 transition-all flex-shrink-0">
          <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 hidden sm:block">Intern 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>
  );
}