'use client';

import React, { useState } from 'react';
import DjangoCSRFToken from '@/components/DjangoCSRFToken';
import Logo from '@/components/Logo';
import InputTextIcon from '@/components/Form/InputTextIcon';
import Loader from '@/components/Loader';
import Button from '@/components/Form/Button';
import { User } from 'lucide-react';
import { FE_USERS_LOGIN_URL } from '@/utils/Url';
import { useCsrfToken } from '@/context/CsrfContext';
import { sendNewPassword } from '@/app/actions/authAction';
import logger from '@/utils/logger';
import { useNotification } from '@/context/NotificationContext';

export default function Page() {
  const { showNotification } = useNotification();
  const [isLoading, setIsLoading] = useState(false);
  const csrfToken = useCsrfToken();

  function validate(formData) {
    const data = { email: formData.get('email') };
    setIsLoading(true);
    sendNewPassword(data, csrfToken)
      .then((data) => {
        logger.debug('Success:', data);
        if (data.message !== '') {
          showNotification(data.message, 'success', 'Succès');
          router.push(`${FE_USERS_LOGIN_URL}`);
        } else {
          if (data.errorMessage) {
            showNotification(data.errorMessage, 'error', 'Erreur');
          } else if (data.errorFields) {
            showNotification(data.errorFields.email, 'error', 'Erreur');
          }
        }
        setIsLoading(false);
      })
      .catch((error) => {
        logger.error('Error fetching data:', error);
        setIsLoading(false);
        error = error.errorMessage;
        logger.debug(error);
      });
  }

  if (isLoading === true) {
    return <Loader />;
  } else {
    return (
      <div className="min-h-screen bg-neutral flex items-center justify-center p-4">
        <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">
            Nouveau Mot de passe
          </h1>
          <form
            onSubmit={(e) => {
              e.preventDefault();
              validate(new FormData(e.target));
            }}
          >
            <DjangoCSRFToken csrfToken={csrfToken} />
            <InputTextIcon
              name="email"
              type="text"
              IconItem={User}
              label="Identifiant"
              placeholder="Identifiant"
              className="w-full mb-6"
            />
            <Button
              text="Réinitialiser"
              className="w-full mb-3"
              primary
              type="submit"
              name="validate"
            />
            <Button
              text="Annuler"
              className="w-full"
              href={`${FE_USERS_LOGIN_URL}`}
            />
          </form>
        </div>
      </div>
    );
  }
}
