'use client';

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 { User, KeySquare } from 'lucide-react';
import { FE_USERS_LOGIN_URL } from '@/utils/Url';
import { useCsrfToken } from '@/context/CsrfContext';
import { subscribe } 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 [isLoading, setIsLoading] = useState(false);

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

  const establishment_id = searchParams.get('establishment_id');

  function subscribeFormSubmit(formData) {
    const data = {
      email: formData.get('login'),
      password1: formData.get('password1'),
      password2: formData.get('password2'),
      establishment_id: establishment_id,
    };
    setIsLoading(true);
    subscribe(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 ||
                data.errorFields.password1 ||
                data.errorFields.password2,
              'error',
              'Erreur'
            );
          }
        }
        setIsLoading(false);
      })
      .catch((error) => {
        setIsLoading(false);
        logger.error('Error fetching data:', error);
        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 profil
          </h1>
          <form
            onSubmit={(e) => {
              e.preventDefault();
              subscribeFormSubmit(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="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"
              onClick={() => router.push(`${FE_USERS_LOGIN_URL}`)}
            />
          </form>
        </div>
      </div>
    );
  }
}
