'use client';
// src/app/pages/subscribe.js

import React, { useState, useEffect } from 'react';
import DjangoCSRFToken from '@/components/DjangoCSRFToken';
import Logo from '@/components/Logo';
import { useSearchParams, useRouter } from 'next/navigation';
import InputTextIcon from '@/components/Form/InputTextIcon';
import Loader from '@/components/Loader';
import Button from '@/components/Form/Button';
import { FE_USERS_LOGIN_URL } from '@/utils/Url';
import { KeySquare } from 'lucide-react';
import { useCsrfToken } from '@/context/CsrfContext';
import { resetPassword } from '@/app/actions/authAction';
import logger from '@/utils/logger';
import { useNotification } from '@/context/NotificationContext';

export default function Page() {
  const searchParams = useSearchParams();
  const { showNotification } = useNotification();
  const uuid = searchParams.get('uuid');
  const [isLoading, setIsLoading] = useState(false);

  const router = useRouter();
  const csrfToken = useCsrfToken();

  function validate(formData) {
    const data = {
      password1: formData.get('password1'),
      password2: formData.get('password2'),
    };
    setIsLoading(true);
    resetPassword(uuid, data, csrfToken)
      .then((data) => {
        if (data.message !== '') {
          logger.debug('Success:', data);
          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.password1 || data.errorFields.password2,
              'error',
              'Erreur'
            );
          }
        }
        setIsLoading(false);
      })
      .catch((error) => {
        logger.error('Error fetching data:', error);
        error = error.errorMessage;
        logger.debug(error);
        setIsLoading(false);
      });
  }

  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">
            Réinitialisation du mot de passe
          </h1>
          <form
            onSubmit={(e) => {
              e.preventDefault();
              validate(new FormData(e.target));
            }}
          >
            <DjangoCSRFToken csrfToken={csrfToken} />
            <InputTextIcon
              name="password1"
              type="password"
              IconItem={KeySquare}
              label="Mot de passe"
              placeholder="Mot de passe"
              className="w-full mb-5"
            />
            <InputTextIcon
              name="password2"
              type="password"
              IconItem={KeySquare}
              label="Confirmation mot de passe"
              placeholder="Confirmation mot de passe"
              className="w-full mb-6"
            />
            <Button
              text="Enregistrer"
              className="w-full mb-3"
              primary
              type="submit"
              name="validate"
            />
            <Button
              text="Annuler"
              className="w-full"
              href={`${FE_USERS_LOGIN_URL}`}
            />
          </form>
        </div>
      </div>
    );
  }
}
