'use client';
import React, { useState, useEffect } from 'react';
import Sidebar from '@/components/Sidebar';
import { usePathname } from 'next/navigation';
import { useTranslations } from 'next-intl';
import {
  LayoutDashboard,
  FileText,
  School,
  Users,
  Award,
  Calendar,
  Settings,
  LogOut,
  MessageSquare,
} from 'lucide-react';

import Popup from '@/components/Popup';
import {
  FE_ADMIN_HOME_URL,
  FE_ADMIN_SUBSCRIPTIONS_URL,
  FE_ADMIN_STRUCTURE_URL,
  FE_ADMIN_DIRECTORY_URL,
  FE_ADMIN_GRADES_URL,
  FE_ADMIN_PLANNING_URL,
  FE_ADMIN_SETTINGS_URL,
  FE_ADMIN_MESSAGERIE_URL,
} from '@/utils/Url';

import { disconnect } from '@/app/actions/authAction';
import ProtectedRoute from '@/components/ProtectedRoute';
import { getGravatarUrl } from '@/utils/gravatar';
import Footer from '@/components/Footer';
import { getRightStr, RIGHTS } from '@/utils/rights';
import { useEstablishment } from '@/context/EstablishmentContext';
import ProfileSelector from '@/components/ProfileSelector';

export default function Layout({ children }) {
  const t = useTranslations('sidebar');
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const { profileRole, establishments, user, clearContext } =
    useEstablishment();

  const sidebarItems = {
    admin: {
      id: 'admin',
      name: t('dashboard'),
      url: FE_ADMIN_HOME_URL,
      icon: LayoutDashboard,
    },
    subscriptions: {
      id: 'subscriptions',
      name: t('subscriptions'),
      url: FE_ADMIN_SUBSCRIPTIONS_URL,
      icon: FileText,
    },
    structure: {
      id: 'structure',
      name: t('structure'),
      url: FE_ADMIN_STRUCTURE_URL,
      icon: School,
    },
    directory: {
      id: 'directory',
      name: t('directory'),
      url: FE_ADMIN_DIRECTORY_URL,
      icon: Users,
    },
    grades: {
      id: 'grades',
      name: t('educational_monitoring'),
      url: FE_ADMIN_GRADES_URL,
      icon: Award,
    },
    planning: {
      id: 'planning',
      name: t('events'),
      url: FE_ADMIN_PLANNING_URL,
      icon: Calendar,
    },
    messagerie: {
      id: 'messagerie',
      name: t('messagerie'),
      url: FE_ADMIN_MESSAGERIE_URL,
      icon: MessageSquare,
    },
    settings: {
      id: 'settings',
      name: t('settings'),
      url: FE_ADMIN_SETTINGS_URL,
      icon: Settings,
    },
  };

  const [isPopupVisible, setIsPopupVisible] = useState(false);

  const pathname = usePathname();
  const currentPage = pathname.split('/').pop();

  const headerTitle = sidebarItems[currentPage]?.name || t('dashboard');

  const softwareName = 'N3WT School';
  const softwareVersion = `${process.env.NEXT_PUBLIC_APP_VERSION}`;

  const handleDisconnect = () => {
    setIsPopupVisible(true);
  };

  const confirmDisconnect = () => {
    setIsPopupVisible(false);
    disconnect();
    clearContext();
  };

  const dropdownItems = [
    {
      type: 'info',
      content: (
        <div className="px-4 py-2">
          <div className="font-medium">{user?.email || 'Utilisateur'}</div>
          <div className="text-xs text-gray-400">
            {getRightStr(profileRole) || ''}
          </div>
        </div>
      ),
    },
    {
      type: 'separator',
      content: <hr className="my-2 border-gray-200" />,
    },
    {
      type: 'item',
      label: 'Déconnexion',
      onClick: handleDisconnect,
      icon: LogOut,
    },
  ];

  const toggleSidebar = () => {
    setIsSidebarOpen(!isSidebarOpen);
  };

  useEffect(() => {
    // Fermer la sidebar quand on change de page sur mobile
    setIsSidebarOpen(false);
  }, [pathname]);

  return (
    <ProtectedRoute requiredRight={[RIGHTS.ADMIN, RIGHTS.TEACHER]}>
      {/* Sidebar */}
      <div
        className={`absolute top-0 bottom-0 left-0 z-30 w-64 bg-white border-r border-gray-200 box-border ${
          isSidebarOpen ? 'block' : 'hidden md:block'
        }`}
      >
        <Sidebar
          establishments={establishments}
          currentPage={currentPage}
          items={Object.values(sidebarItems)}
          onCloseMobile={toggleSidebar}
        />
      </div>

      {/* Overlay for mobile */}
      {isSidebarOpen && (
        <div
          className="fixed inset-0 bg-black bg-opacity-50 z-20 md:hidden"
          onClick={toggleSidebar}
        />
      )}

      {/* Main container */}
      <div className="absolute overflow-auto bg-gradient-to-br from-emerald-50 via-sky-50 to-emerald-100 top-0 bottom-16 left-64 right-0">
        {children}
      </div>

      {/* Footer */}
      <Footer softwareName={softwareName} softwareVersion={softwareVersion} />

      <Popup
        isOpen={isPopupVisible}
        message="Êtes-vous sûr(e) de vouloir vous déconnecter ?"
        onConfirm={confirmDisconnect}
        onCancel={() => setIsPopupVisible(false)}
      />
    </ProtectedRoute>
  );
}
