'use client';
import React, { useState, useEffect } from 'react';
import Tab from '@/components/Tab';
import TabContent from '@/components/TabContent';
import Button from '@/components/Button';
import InputText from '@/components/InputText';
import CheckBox from '@/components/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';
import { useSearchParams } from 'next/navigation'; // Ajoute cet import

export default function SettingsPage() {
  const [activeTab, setActiveTab] = useState('smtp');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  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();
  const searchParams = useSearchParams();

  const handleTabClick = (tab) => {
    setActiveTab(tab);
  };

  // Ajout : sélection automatique de l'onglet via l'ancre ou le paramètre de recherche
  useEffect(() => {
    const tabParam = searchParams.get('tab');
    if (tabParam === 'smtp') {
      setActiveTab('smtp');
    }
  }, [searchParams]);

  // Charger les paramètres SMTP existants
  useEffect(() => {
    if (activeTab === 'smtp') {
      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'
            );
          }
        });
    }
  }, [activeTab, csrfToken]); // Ajouter csrfToken comme dépendance

  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-8">
      <div className="flex space-x-4 mb-4">
        <Tab
          text="Paramètres SMTP"
          active={activeTab === 'smtp'}
          onClick={() => handleTabClick('smtp')}
        />
      </div>
      <div className="mt-4">
        <TabContent isActive={activeTab === 'smtp'}>
          <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>
        </TabContent>
      </div>
    </div>
  );
}
