'use client'
// src/components/Layout.js
import React, { useState, useEffect } from 'react';
import DropdownMenu from '@/components/DropdownMenu';
import { useRouter } from 'next/navigation'; // Ajout de l'importation
import { User, MessageSquare, LogOut, Settings, Home } from 'lucide-react'; // Ajout de l'importation de l'icône Home
import Logo from '@/components/Logo'; // Ajout de l'importation du composant Logo
import { FE_PARENTS_HOME_URL,FE_PARENTS_MESSAGERIE_URL,FE_PARENTS_SETTINGS_URL  } from '@/utils/Url'; // Ajout de l'importation de l'URL de la page d'accueil parent
import { fetchMessages } from '@/app/actions/messagerieAction';
import ProtectedRoute from '@/components/ProtectedRoute';
import { disconnect } from '@/app/actions/authAction';
import Popup from '@/components/Popup';
import logger from '@/utils/logger';
import { useSession } from 'next-auth/react';
import { FE_USERS_LOGIN_URL } from '@/utils/Url';
import { getRightStr, RIGHTS } from '@/utils/rights';
import { getGravatarUrl } from '@/utils/gravatar';
import Image from 'next/image';

export default function Layout({
  children,
}) {

  const router = useRouter(); // Définition de router
  const [messages, setMessages] = useState([]);
  const { data: session, status } = useSession();
  const [userId, setUserId] = useState(null);
  const [user, setUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isPopupVisible, setIsPopupVisible] = useState(false);

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

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

  // useEffect(() => {
  //     if (status === 'loading') return;
  //     if (!session) {
  //       router.push(`${FE_USERS_LOGIN_URL}`);
  //     }

  //     const userIdFromSession = session.user.id;
  //     setUserId(userIdFromSession);
  //     setIsLoading(true);
  //     fetchMessages(userId)
  //       .then(data => {
  //         if (data) {
  //           setMessages(data);
  //         }
  //         logger.debug('Success :', data);
  //       })
  //       .catch(error => {
  //         logger.error('Error fetching data:', error);
  //       })
  //       .finally(() => {
  //         setIsLoading(false);
  //       });
  // }, [userId]);

  // if (isLoading) {
  //   return <div>Loading...</div>;
  // }
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(user?.roles[0]?.role_type) || ''}</div>
        </div>
      )
    },
    {
      type: 'separator',
      content: <hr className="my-2 border-gray-200" />
    },
    { label: 'Settings', icon: Settings , onClick: () => { router.push(FE_PARENTS_SETTINGS_URL); } },
    {
      type: 'item',
      label: 'Déconnexion',
      onClick: handleDisconnect,
      icon: LogOut,
    },
  ];
  return (
      <ProtectedRoute requiredRight={RIGHTS.PARENT}>
      <div className="flex flex-col min-h-screen bg-gray-50">
        {/* Entête */}
        <header className="bg-white border-b border-gray-200 px-4 py-2 md:px-8 md:py-4 flex items-center justify-between fixed top-0 left-0 right-0 z-10">
            <div className="flex items-center space-x-2">
              <Logo className="h-6 w-6 md:h-8 md:w-8" /> {/* Utilisation du composant Logo */}

              <div className="text-lg md:text-xl font-semibold">Accueil</div>
            </div>
            <div className="flex items-center space-x-2 md:space-x-4">
              <button
                  className="p-1 md:p-2 rounded-full hover:bg-gray-200"
                  onClick={() => { router.push(FE_PARENTS_HOME_URL); }} // Utilisation de router pour revenir à l'accueil parent
                >
                  <Home className="h-5 w-5 md:h-6 md:w-6" />
              </button>

              <div className="relative">
              <button
                className="p-1 md:p-2 rounded-full hover:bg-gray-200"
                onClick={() => { router.push(FE_PARENTS_MESSAGERIE_URL); }} // Utilisation de router
              >
                <MessageSquare className="h-5 w-5 md:h-6 md:w-6" />
              </button>
               {messages.length > 0 && (
                  <span className="absolute top-0 right-0 block h-2 w-2 rounded-full bg-emerald-600"></span>
                )}
              </div>
              <DropdownMenu
                buttonContent={<Image
                    src={getGravatarUrl(user?.email)}
                    alt="Profile"
                    className="w-8 h-8 rounded-full cursor-pointer"
                    width={32}
                    height={32}
                  />}
                items={dropdownItems}
                buttonClassName=""
                menuClassName="absolute right-0 mt-2 w-64 bg-white border border-gray-200 rounded shadow-lg"
              />
            </div>
        </header>

        {/* Content */}
        <div className="pt-16 md:pt-20 p-4 md:p-8 flex-1"> {/* Ajout de flex-1 pour utiliser toute la hauteur disponible */}
          {children}
        </div>
      </div>
      <Popup
          visible={isPopupVisible}
          message="Êtes-vous sûr(e) de vouloir vous déconnecter ?"
          onConfirm={confirmDisconnect}
          onCancel={() => setIsPopupVisible(false)}
        />
      </ProtectedRoute>
  );
}


