'use client';
import React, { useState } from 'react';
import DjangoCSRFToken from '@/components/DjangoCSRFToken';
import Logo from '@/components/Logo';
import { useRouter } from 'next/navigation';
import InputTextIcon from '@/components/Form/InputTextIcon';
import Loader from '@/components/Loader'; // Importez le composant Loader
import Button from '@/components/Form/Button'; // Importez le composant Button
import { User, KeySquare } from 'lucide-react'; // Importez directement les icônes nécessaires
import { FE_USERS_NEW_PASSWORD_URL, getRedirectUrlFromRole } from '@/utils/Url';
import { login } from '@/app/actions/authAction';
import { getSession } from 'next-auth/react';
import { useCsrfToken } from '@/context/CsrfContext'; // Importez le hook useCsrfToken
import logger from '@/utils/logger';

import { useEstablishment } from '@/context/EstablishmentContext';
import { useNotification } from '@/context/NotificationContext';

export default function Page() {
  const { initializeContextWithSession } = useEstablishment();
  const [isLoading, setIsLoading] = useState(false);

  const router = useRouter();
  const csrfToken = useCsrfToken(); // Utilisez le hook useCsrfToken
  const { showNotification } = useNotification();

  function handleFormLogin(formData) {
    setIsLoading(true);

    login({
      email: formData.get('login'),
      password: formData.get('password'),
    })
      .then((result) => {
        logger.debug('Sign In Result', result);

        if (result.error) {
          showNotification(result.error, 'error', 'Erreur');
          setIsLoading(false);
        } else {
          // On initialise le contexte establishement avec la session
          getSession()
            .then((session) => {
              initializeContextWithSession(session, (role) => {
                const url = getRedirectUrlFromRole(role);
                if (url) {
                  router.push(url);
                } else {
                  showNotification('Type de rôle non géré', 'error', 'Erreur');
                }
              });
              setIsLoading(false);
            })
            .catch((error) => {
              logger.error(
                'Erreur lors de la récupération de la session:',
                error
              );
              setIsLoading(false);
              showNotification(
                'Une erreur est survenue lors de la récupération de la session.',
                'error',
                'Erreur'
              );
            });
        }
      })
      .catch((error) => {
        logger.error('Erreur lors de la connexion:', error);
        setIsLoading(false);
        showNotification(
          'Une erreur est survenue lors de la connexion.',
          'error',
          'Erreur'
        );
      });
  }

  if (isLoading === true) {
    return <Loader />; // Affichez le composant Loader
  } else {
    return (
      <div className="min-h-screen flex items-center justify-center p-4 bg-neutral">
        <div className="bg-white rounded-md border border-gray-200 shadow-sm p-8 w-full max-w-md">
          <div className="flex justify-center mb-6">
            <Logo className="h-150 w-150" />
          </div>
          <h1 className="font-headline text-2xl font-bold text-center text-gray-900 mb-6">
            Authentification
          </h1>
          <form
            onSubmit={(e) => {
              e.preventDefault();
              handleFormLogin(new FormData(e.target));
            }}
          >
            <DjangoCSRFToken csrfToken={csrfToken} />
            <InputTextIcon
              name="login"
              type="text"
              IconItem={User}
              label="Identifiant"
              placeholder="Identifiant"
              className="w-full mb-5"
            />
            <InputTextIcon
              name="password"
              type="password"
              IconItem={KeySquare}
              label="Mot de passe"
              placeholder="Mot de passe"
              className="w-full mb-5"
            />
            <div className="flex justify-end mb-4">
              <a
                className="text-sm text-primary hover:text-secondary font-label transition-colors"
                href={`${FE_USERS_NEW_PASSWORD_URL}`}
              >
                Mot de passe oublié ?
              </a>
            </div>
            <Button
              text="Se Connecter"
              className="w-full"
              primary
              type="submit"
              name="connect"
            />
          </form>
        </div>
      </div>
    );
  }
}
