'use client';
import React, { useState, useEffect } from 'react';
import Button from '@/components/Form/Button';
import InputText from '@/components/Form/InputText';
import CheckBox from '@/components/Form/CheckBox'; // Import du composant CheckBox
import logger from '@/utils/logger';
import {
  fetchSmtpSettings,
  editSmtpSettings,
} from '@/app/actions/settingsAction';
import { useEstablishment } from '@/context/EstablishmentContext';
import { useCsrfToken } from '@/context/CsrfContext'; // Import du hook pour récupérer le csrfToken
import { useNotification } from '@/context/NotificationContext';

export default function SettingsPage() {
  const [smtpServer, setSmtpServer] = useState('');
  const [smtpPort, setSmtpPort] = useState('');
  const [smtpUser, setSmtpUser] = useState('');
  const [smtpPassword, setSmtpPassword] = useState('');
  const [useTls, setUseTls] = useState(true);
  const [useSsl, setUseSsl] = useState(false);
  const { selectedEstablishmentId } = useEstablishment();
  const csrfToken = useCsrfToken(); // Récupération du csrfToken
  const { showNotification } = useNotification();

  // Charger les paramètres SMTP existants
  useEffect(() => {
    if (csrfToken && selectedEstablishmentId) {
      fetchSmtpSettings(csrfToken, selectedEstablishmentId) // Passer le csrfToken ici
        .then((data) => {
          setSmtpServer(data.smtp_server || '');
          setSmtpPort(data.smtp_port || '');
          setSmtpUser(data.smtp_user || '');
          setSmtpPassword(data.smtp_password || '');
          setUseTls(data.use_tls || false);
          setUseSsl(data.use_ssl || false);
        })
        .catch((error) => {
          if (error.response && error.response.status === 404) {
            showNotification(
              "Les données SMTP n'ont pas été trouvées.",
              'warning',
              'Attention'
            );
          } else {
            logger.error(
              'Erreur lors du chargement des paramètres SMTP:',
              error
            );
            showNotification(
              'Erreur lors du chargement des paramètres SMTP.',
              'error',
              'Erreur'
            );
          }
        });
    }
  }, [csrfToken, selectedEstablishmentId]);

  const handleSmtpServerChange = (e) => {
    setSmtpServer(e.target.value);
  };

  const handleSmtpPortChange = (e) => {
    setSmtpPort(e.target.value);
  };

  const handleSmtpUserChange = (e) => {
    setSmtpUser(e.target.value);
  };

  const handleSmtpPasswordChange = (e) => {
    setSmtpPassword(e.target.value);
  };

  const handleSmtpSubmit = (e) => {
    e.preventDefault();
    const smtpData = {
      establishment: selectedEstablishmentId,
      smtp_server: smtpServer,
      smtp_port: smtpPort,
      smtp_user: smtpUser,
      smtp_password: smtpPassword,
      use_tls: useTls,
      use_ssl: useSsl,
    };

    editSmtpSettings(smtpData, csrfToken) // Passer le csrfToken ici
      .then(() => {
        showNotification(
          'Paramètres SMTP mis à jour avec succès.',
          'success',
          'Succès'
        );
        logger.debug('SMTP Settings Updated:', smtpData);
      })
      .catch((error) => {
        logger.error(
          'Erreur lors de la mise à jour des paramètres SMTP:',
          error
        );
        showNotification(
          'Erreur lors de la mise à jour des paramètres SMTP.',
          'error',
          'Erreur'
        );
      });
  };

  return (
    <div className="p-6">
      <h1 className="font-headline text-2xl font-bold text-gray-900 mb-6">
        Paramètres
      </h1>
      <div className="bg-white rounded-md border border-gray-200 shadow-sm p-6">
        <h2 className="font-headline text-lg font-semibold text-gray-800 mb-4">
          Paramètres SMTP
        </h2>
        <form onSubmit={handleSmtpSubmit}>
          <div className="grid grid-cols-2 gap-4">
            <InputText
              label="Serveur SMTP"
              value={smtpServer}
              onChange={handleSmtpServerChange}
            />
            <InputText
              label="Port SMTP"
              value={smtpPort}
              onChange={handleSmtpPortChange}
            />
            <InputText
              label="Utilisateur SMTP"
              value={smtpUser}
              onChange={handleSmtpUserChange}
            />
            <InputText
              label="Mot de passe SMTP"
              type="password"
              value={smtpPassword}
              onChange={handleSmtpPasswordChange}
            />
          </div>
          <div className="mt-6 border-t pt-4">
            <div className="flex items-center space-x-4">
              <CheckBox
                item={{ id: 'useTls' }}
                formData={{ useTls }}
                handleChange={() => setUseTls((prev) => !prev)} // Inverser la valeur booléenne
                fieldName="useTls"
                itemLabelFunc={() => 'Utiliser TLS'}
              />
              <CheckBox
                item={{ id: 'useSsl' }}
                formData={{ useSsl }}
                handleChange={() => setUseSsl((prev) => !prev)} // Inverser la valeur booléenne
                fieldName="useSsl"
                itemLabelFunc={() => 'Utiliser SSL'}
              />
            </div>
          </div>
          <Button
            type="submit"
            primary
            text="Mettre à jour"
            className="mt-6"
          ></Button>
        </form>
      </div>
    </div>
  );
}
