// filepath: d:\Dev\n3wt-innov\n3wt-school\Front-End\src\components\Admin\InstantMessaging.js
import React, { useEffect, useState } from 'react';
import Chat from '@/components/Chat';
import { useEstablishment } from '@/context/EstablishmentContext';
import {
  fetchConversations,
  sendMessage,
  searchRecipients,
} from '@/app/actions/messagerieAction';
import RecipientInput from '@/components/RecipientInput';
import Modal from '@/components/Modal';

export default function InstantMessaging({ csrfToken }) {
  const { user, selectedEstablishmentId } = useEstablishment();
  const [discussions, setDiscussions] = useState([]);
  const [recipients, setRecipients] = useState([]); // Liste des correspondants sélectionnés
  const [showModal, setShowModal] = useState(false);
  const [firstMessage, setFirstMessage] = useState('');

  useEffect(() => {
    if (user) {
      fetchConversations(user.id).then(setDiscussions);
    }
  }, [user]);

  // Fonction pour ajouter une nouvelle discussion avec plusieurs correspondants
  const handleCreateDiscussion = async () => {
    if (!user || recipients.length === 0 || !firstMessage.trim()) return;
    for (const recipient of recipients) {
      await sendMessage({
        emetteur: user.id,
        destinataire: recipient.id,
        objet: '',
        corpus: firstMessage,
        conversation_id: undefined, // L'API générera un nouvel ID
      });
    }
    setRecipients([]);
    setFirstMessage('');
    setShowModal(false);
    fetchConversations(user.id).then(setDiscussions);
  };

  if (!user) return <div>Chargement...</div>;

  return (
    <div className="h-full w-full">
      <Chat
        userProfileId={user.id}
        establishmentId={selectedEstablishmentId}
        discussions={discussions}
        setDiscussions={setDiscussions}
        onShowCreateDiscussion={() => setShowModal(true)}
      />
      <Modal
        isOpen={showModal}
        setIsOpen={setShowModal}
        title="Nouvelle discussion"
        modalClassName="w-full max-w-xs sm:max-w-md"
      >
        <div className="p-2 sm:p-4">
          <h3 className="text-lg font-bold mb-2">Nouvelle discussion</h3>
          <RecipientInput
            label="Rechercher un correspondant"
            recipients={recipients}
            setRecipients={setRecipients}
            searchRecipients={searchRecipients}
            establishmentId={selectedEstablishmentId}
            required
          />
          <input
            type="text"
            value={firstMessage}
            onChange={(e) => setFirstMessage(e.target.value)}
            placeholder="Premier message"
            className="w-full p-2 mb-2 border rounded"
          />
          <button
            onClick={handleCreateDiscussion}
            className="w-full p-2 bg-green-500 text-white rounded-lg"
          >
            Démarrer la discussion
          </button>
        </div>
      </Modal>
    </div>
  );
}
