'use client';
// src/components/Layout.js
import React, { useState, useEffect } from 'react';
import Sidebar from '@/components/Sidebar';
import { useRouter, usePathname } from 'next/navigation';
import { MessageSquare, Settings, Home } from 'lucide-react';
import { FE_PARENTS_HOME_URL, FE_PARENTS_MESSAGERIE_URL } from '@/utils/Url';
import ProtectedRoute from '@/components/ProtectedRoute';
import { disconnect } from '@/app/actions/authAction';
import Popup from '@/components/Popup';
import MobileTopbar from '@/components/MobileTopbar';
import { RIGHTS } from '@/utils/rights';
import { useEstablishment } from '@/context/EstablishmentContext';
import Footer from '@/components/Footer';
import { useChatConnection } from '@/context/ChatConnectionContext';

export default function Layout({ children }) {
  const router = useRouter();
  const pathname = usePathname();
  const [isPopupVisible, setIsPopupVisible] = useState(false);
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const { clearContext } = useEstablishment();
  const { totalUnreadCount, resetUnreadCount } = useChatConnection();
  const softwareName = 'N3WT School';
  const softwareVersion = `${process.env.NEXT_PUBLIC_APP_VERSION}`;

  // Vérifier si on est sur la page messagerie
  const isMessagingPage = pathname?.includes('/messagerie');

  // Configuration des éléments de la sidebar pour les parents
  const sidebarItems = [
    {
      id: 'home',
      name: 'Accueil',
      url: FE_PARENTS_HOME_URL,
      icon: Home,
    },
    {
      id: 'messagerie',
      name: 'Messagerie',
      url: FE_PARENTS_MESSAGERIE_URL,
      icon: MessageSquare,
      badge: totalUnreadCount,
    },
  ];

  // Déterminer la page actuelle pour la sidebar
  const getCurrentPage = () => {
    if (pathname?.includes('/messagerie')) return 'messagerie';
    if (pathname?.includes('/settings')) return 'settings';
    return 'home';
  };

  const currentPage = getCurrentPage();

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

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

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

  useEffect(() => {
    // Fermer la sidebar quand on change de page sur mobile
    setIsSidebarOpen(false);
    // Réinitialiser le compteur non lu quand on ouvre la messagerie
    if (pathname?.includes('/messagerie')) {
      resetUnreadCount();
    }
  }, [pathname, resetUnreadCount]);

  return (
    <ProtectedRoute requiredRight={RIGHTS.PARENT}>
      {/* Topbar mobile (hamburger + logo) */}
      <MobileTopbar onMenuClick={toggleSidebar} />

      {/* Sidebar */}
      <div
        className={`absolute top-14 md: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
          currentPage={currentPage}
          items={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-primary/5 via-sky-50 to-primary/10 top-14 md:top-0 bottom-16 left-0 md:left-64 right-0 ${!isMessagingPage ? 'p-4 md:p-8' : ''}`}
      >
        {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>
  );
}
