'use client';

import React, { useState, useEffect } from 'react';
import dynamic from 'next/dynamic';
import { sendEmail, searchRecipients } from '@/app/actions/emailAction';
import { fetchSmtpSettings } from '@/app/actions/settingsAction';
import { useNotification } from '@/context/NotificationContext';
import { useEstablishment } from '@/context/EstablishmentContext';
import AlertMessage from '@/components/AlertMessage';
import RecipientInput from '@/components/RecipientInput';
import { useRouter } from 'next/navigation'; // Ajoute cette ligne
import WisiwigTextArea from '@/components/Form/WisiwigTextArea';
import logger from '@/utils/logger';
import InputText from '@/components/Form/InputText';
import Button from '@/components/Form/Button';

export default function EmailSender({ csrfToken }) {
  const [recipients, setRecipients] = useState([]);
  const [fromEmail, setFromEmail] = useState('');
  const [cc, setCc] = useState([]);
  const [bcc, setBcc] = useState([]);
  const [subject, setSubject] = useState('');
  const [message, setMessage] = useState('');
  const [smtpConfigured, setSmtpConfigured] = useState(false); // État pour vérifier si SMTP est configuré
  const { showNotification } = useNotification();
  const { selectedEstablishmentId } = useEstablishment(); // Récupérer l'establishment_id depuis le contexte
  const router = useRouter(); // Ajoute cette ligne

  useEffect(() => {
    // Vérifier si les paramètres SMTP sont configurés
    fetchSmtpSettings(csrfToken, selectedEstablishmentId)
      .then((data) => {
        if (data.smtp_server && data.smtp_port && data.smtp_user) {
          setFromEmail(data.smtp_user);
          setSmtpConfigured(true);
        } else {
          setSmtpConfigured(false);
        }
      })
      .catch((error) => {
        logger.error('Erreur lors de la vérification des paramètres SMTP:', {
          error,
        });
        setSmtpConfigured(false);
      });
  }, [csrfToken, selectedEstablishmentId]);

  const handleSendEmail = async () => {
    const data = {
      recipients,
      cc,
      bcc,
      subject,
      message,
      establishment_id: selectedEstablishmentId, // Ajouter l'establishment_id à la payload
    };

    try {
      await sendEmail(data);
      showNotification('Email envoyé avec succès.', 'success', 'Succès');
      // Réinitialiser les champs après succès
      setRecipients([]);
      setCc([]);
      setBcc([]);
      setSubject('');
      setMessage('');
    } catch (error) {
      logger.error("Erreur lors de l'envoi de l'email:", { error });
      showNotification(
        "Une erreur est survenue lors de l'envoi de l'email.",
        'error',
        'Erreur'
      );
    }
  };

  if (!smtpConfigured) {
    return (
      <AlertMessage
        type="warning"
        title="Configuration SMTP requise"
        message="Les paramètres SMTP de cet établissement ne sont pas configurés. Veuillez les configurer dans la page des paramètres."
        actionLabel="Aller aux paramètres"
        onAction={() => router.push('/admin/settings?tab=smtp')} // Utilise next/navigation ici
      />
    );
  }

  return (
    <div className="max-w-3xl mx-auto bg-white rounded-lg shadow-md">
      {/* Form */}
      <div className="p-4 flex flex-col min-h-[600px]">
        {' '}
        {/* Ajout flex-col et min-h */}
        {/* Destinataires */}
        <RecipientInput
          label="Destinataires"
          recipients={recipients}
          setRecipients={setRecipients}
          searchRecipients={searchRecipients}
          establishmentId={selectedEstablishmentId}
          required
        />
        {/* Cc */}
        <div className="mt-2">
          <RecipientInput
            label="Cc"
            placeholder="Ajouter Cc"
            recipients={cc}
            searchRecipients={searchRecipients}
            establishmentId={selectedEstablishmentId}
            setRecipients={setCc}
          />
        </div>
        {/* Bcc */}
        <div className="mt-2">
          <RecipientInput
            label="Cci"
            placeholder="Ajouter Bcc"
            recipients={bcc}
            searchRecipients={searchRecipients}
            establishmentId={selectedEstablishmentId}
            setRecipients={setBcc}
          />
        </div>
        {/* Subject */}
        <InputText
          name="subject"
          label="Sujet"
          value={subject}
          onChange={(e) => setSubject(e.target.value)}
          placeholder="Saisir le sujet"
          className="mb-4 mt-2"
          required
        />
        {/* Email Body */}
        <div className="mb-4 flex flex-col">
          <WisiwigTextArea
            label="Mail"
            value={message}
            onChange={setMessage}
            placeholder="Ecrivez votre mail ici..."
            required
          />
        </div>
        {/* Footer */}
        <div className="flex justify-between items-center mt-10">
          <Button
            text="Envoyer"
            onClick={handleSendEmail}
            primary
            className="px-4 py-2"
          />
        </div>
      </div>
    </div>
  );
}
