'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('structure');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [smtpServer, setSmtpServer] = useState('');
  const [imapServer, setImapServer] = useState('');
  const [smtpPort, setSmtpPort] = useState('');
  const [imapPort, setImapPort] = useState('');
  const [mailUser, setMailUser] = useState('');
  const [mailPassword, setMailPassword] = useState('');
  const [useTls, setUseTls] = useState(true);
  const [useSsl, setUseSsl] = useState(false);
  const { user, 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');
    } else if (tabParam === 'structure') {
      setActiveTab('structure');
    }
  }, [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 || '');
          setImapServer(data.imap_server || '');
          setImapPort(data.imap_port || '');
          setMailUser(data.mail_user || '');
          setMailPassword(data.mail_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 handleEmailChange = (e) => {
    setEmail(e.target.value);
  };

  const handlePasswordChange = (e) => {
    setPassword(e.target.value);
  };

  const handleConfirmPasswordChange = (e) => {
    setConfirmPassword(e.target.value);
  };

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

  const handleImapServerChange = (e) => {
    setImapServer(e.target.value);
  };

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

  const handleImapPortChange = (e) => {
    setImapPort(e.target.value);
  };

  const handleMailUserChange = (e) => {
    setMailUser(e.target.value);
  };

  const handleMailPasswordChange = (e) => {
    setMailPassword(e.target.value);
  };

  const handleUseTlsChange = (e) => {
    setUseTls(e.target.checked);
  };

  const handleUseSslChange = (e) => {
    setUseSsl(e.target.checked);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (password !== confirmPassword) {
      showNotification(
        'Les mots de passe ne correspondent pas',
        'error',
        'Erreur'
      );
      return;
    }
  };

  const handleSmtpSubmit = (e) => {
    e.preventDefault();
    const smtpData = {
      establishment: selectedEstablishmentId,
      profile_id: user.user_id,
      smtp_server: smtpServer,
      smtp_port: smtpPort,
      imap_server: imapServer,
      imap_port: imapPort,
      mail_user: mailUser,
      mail_password: mailPassword,
      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="Informations de la structure"
          active={activeTab === 'structure'}
          onClick={() => handleTabClick('structure')}
        />
        <Tab
          text="Paramètres SMTP"
          active={activeTab === 'smtp'}
          onClick={() => handleTabClick('smtp')}
        />
      </div>
      <div className="mt-4">
        <TabContent isActive={activeTab === 'structure'}>
          <form onSubmit={handleSubmit}>
            <InputText
              label="Email"
              value={email}
              onChange={handleEmailChange}
            />
            <InputText
              label="Mot de passe"
              type="password"
              value={password}
              onChange={handlePasswordChange}
            />
            <InputText
              label="Confirmer le mot de passe"
              type="password"
              value={confirmPassword}
              onChange={handleConfirmPasswordChange}
            />
            <Button type="submit" primary text="Mettre à jour"></Button>
          </form>
        </TabContent>
        <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="Serveur IMAP"
                value={imapServer}
                onChange={handleImapServerChange}
              />
              <InputText
                label="Port IMAP"
                value={imapPort}
                onChange={handleImapPortChange}
              />
              <InputText
                label="Adresse mail"
                value={mailUser}
                onChange={handleMailUserChange}
              />
              <InputText
                label="Mot de passe"
                type="password"
                value={mailPassword}
                onChange={handleMailPasswordChange}
              />
            </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>
  );
}
