'use client';

import { useEffect, useState, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/context/AuthContext';
import Sidebar from '@/components/Sidebar';

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const { user, isLoading, isAuthenticated, logout } = useAuth();
  const router = useRouter();
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!isLoading && !isAuthenticated) {
      router.push('/login');
    }
  }, [isAuthenticated, isLoading, router]);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsDropdownOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleLogout = async () => {
    setIsDropdownOpen(false);
    await logout();
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-[#f5f9f8]">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#f5a623]"></div>
      </div>
    );
  }

  if (!isAuthenticated) {
    return null;
  }

  return (
    <div className="min-h-screen bg-[#f5f9f8]">
      {/* Sidebar */}
      <Sidebar />

      {/* Main Content */}
      <div className="ml-64">
        {/* Top Header */}
        <header className="bg-white border-b border-[#e5e7eb] sticky top-0 z-40">
          <div className="px-8 py-3">
            <div className="flex justify-end items-center">
              {/* User Dropdown */}
              <div className="relative" ref={dropdownRef}>
                <button
                  onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                  className="flex items-center gap-3 py-2 px-3 rounded-xl hover:bg-[#f5f9f8] transition-all duration-200"
                >
                  <div className="w-9 h-9 bg-[#00293d] rounded-full flex items-center justify-center shadow-sm">
                    <span className="text-white font-semibold text-sm font-fractul">
                      {user?.firstName?.[0] || user?.email?.[0]?.toUpperCase() || 'A'}
                    </span>
                  </div>
                  <div className="text-left hidden sm:block">
                    <p className="text-sm font-semibold text-[#00293d] font-fractul">
                      {user?.firstName || 'Admin'} {user?.lastName || ''}
                    </p>
                    <p className="text-xs text-[#666666] font-serif">{user?.email}</p>
                  </div>
                  <svg
                    className={`w-4 h-4 text-[#9ca3af] transition-transform duration-200 ${isDropdownOpen ? 'rotate-180' : ''}`}
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                </button>

                {/* Dropdown Menu */}
                {isDropdownOpen && (
                  <div className="absolute right-0 mt-2 w-56 bg-white rounded-xl shadow-lg border border-[#e5e7eb] overflow-hidden z-50">
                    <div className="px-4 py-4 bg-[#f5f9f8] border-b border-[#e5e7eb]">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-[#00293d] rounded-full flex items-center justify-center shadow-sm">
                          <span className="text-white font-semibold font-fractul">
                            {user?.firstName?.[0] || user?.email?.[0]?.toUpperCase() || 'A'}
                          </span>
                        </div>
                        <div>
                          <p className="text-sm font-semibold text-[#00293d] font-fractul">
                            {user?.firstName || 'Admin'} {user?.lastName || ''}
                          </p>
                          <p className="text-xs text-[#666666] truncate font-serif">{user?.email}</p>
                        </div>
                      </div>
                    </div>
                    <div className="p-2">
                      <button
                        onClick={handleLogout}
                        className="w-full px-3 py-2.5 text-left text-sm text-red-600 hover:bg-red-50 rounded-lg flex items-center gap-3 transition-colors duration-150"
                      >
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                        </svg>
                        Sign out
                      </button>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </header>

        {/* Page Content */}
        <main className="p-8">{children}</main>
      </div>
    </div>
  );
}
