import styles from './index.module.scss';
import axios from "axios";
import {useRouter} from "next/router";
import {SubmitHandler, useForm} from 'react-hook-form';
import {BehaviorSubject, catchError, debounceTime, distinctUntilChanged, filter, map, of, switchMap} from "rxjs";
import {useEffect, useState} from "react";

import SeoConfig from "../../components/seo-config/seo-config";
import Layout from "../../components/layout/layout";
import {Inputs, signUpRequest} from "../../libs/api";
import {createJwtToken} from "../../libs/auth";

export function SignUp({seo, menuHeader, menuFooter}) {
  const router = useRouter();
  const {register, handleSubmit, getValues, formState: {errors}, setError, clearErrors} = useForm({
    defaultValues: {
      email: "",
      username: "",
      password: "",
      passwordConfirmation: "",
      agreement: false,
      newsletter: false,
    }
  });
  const [spinner, setSpinner] = useState(false);
  const [subject, setSubject] = useState(null);

  useEffect(() => {
    if (subject === null) {
      const sub = new BehaviorSubject('');
      setSubject(sub);
    } else {
      subject.pipe(
        map((s: string) => s.trim()),
        distinctUntilChanged(),
        filter((s: string) => s.length >= 2),
        debounceTime(200),
        switchMap(async (value) => {
          setSpinner(true);
          const result = await axios.get(`http://localhost:1337/api/username/${value}`)
          if (result.data) {
            setError('email', {type: 'custom', message: "Cet email est déjà utilisé. Veuillez en saisir un autre."});
          } else {
            clearErrors('email');
          }
        }),
        catchError((err) => of(false))
      ).subscribe(() => setSpinner(false));
    }
  }, [subject]);

  const onSubmit: SubmitHandler<Inputs> = async (data: Inputs) => {
    try {
      const response = await signUpRequest(data);
      if (response && response.user) {
        if (response.user.confirmed) {
          const result = await createJwtToken(data.email, data.password);
          if (result.ok) {
            await router.replace('/');
            return;
          }
        } else {
          await router.push('/signup-confirmation')
          return;
        }
      } else {
        throw new Error('no registered');
      }
    } catch (e) {
      console.error(e);
    }
  };

  const onEmailChange = (e) => subject.next(e.target.value);

  const hasErrors = () => Object.keys(errors).length > 0;

  return (
    <>
      <SeoConfig {...seo}/>
      <Layout menuHeader={menuHeader} menuFooter={menuFooter}>
        <div className={styles['page-sign-up']}>
          <section className={styles['section']}>
            <div className="container px-6 py-4 md:py-12 h-full mx-auto">
              <div className="flex justify-center items-center flex-wrap h-full g-6 text-gray-800">
                <div className="md:w-8/12 lg:w-6/12">
                  <div
                    className="w-full max-w-[560px] p-4 bg-white border border-gray-200 rounded-lg shadow-md sm:p-6 md:p-8 dark:bg-gray-800 dark:border-gray-700">
                    <form className="space-y-6" onSubmit={handleSubmit(onSubmit)}>
                      <header className="text-left block">
                        <h3 className="text-3xl font-normal dark:text-white mb-6">Création de votre compte</h3>
                        <p className="mb-6 text-base font-normal text-gray-500 dark:text-gray-400">
                          Créez un compte gratuit 100% sécurisé. <br/>Vous avez déjà un compte ? <a href="/sign-in"
                                                                                                    className="font-medium text-blue-600 dark:text-blue-500 hover:underline"
                                                                                                    target="_self">
                          Connectez-vous ici
                        </a>.
                        </p>
                      </header>
                      <main>
                        <section className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div>
                            <label htmlFor="email"
                                   className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
                              E-mail
                            </label>
                            <div className="relative">
                              {spinner && (
                                <div className="absolute inset-y-0 right-0 flex items-center pr-1 pointer-events-none">
                                  <svg aria-hidden="true"
                                       className="w-5 h-5 mr-2 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600"
                                       viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path
                                      d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
                                      fill="currentColor"/>
                                    <path
                                      d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
                                      fill="currentFill"/>
                                  </svg>
                                  <span className="sr-only">Loading...</span>
                                </div>)}
                              <input type="email"
                                     name="email"
                                     id="email"
                                     {...register("email", {required: "L'email est requis"})}
                                     onChange={onEmailChange}
                                     className={errors.email ? 'bg-red-50 border border-red-500 text-red-900 placeholder-red-700 text-sm rounded-lg focus:ring-red-500 dark:bg-gray-700 focus:border-red-500 block w-full p-2.5 dark:text-red-500 dark:placeholder-red-500 dark:border-red-500' : 'bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full pr-10 p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white'}
                                     placeholder="name@company.com"/>
                              {errors.email && (
                                <p className="mt-2 text-sm text-red-600 dark:text-red-500">{errors.email.message}</p>)}
                            </div>
                          </div>
                          <div>
                            <label htmlFor="username"
                                   className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
                              Nom d&apos;utilisateur
                            </label>
                            <input type="text"
                                   name="username"
                                   id="username"
                                   {...register("username", {required: "Le nom d'utilisateur est requis"})}
                                   className={errors.username ? "bg-red-50 border border-red-500 text-red-900 placeholder-red-700 text-sm rounded-lg focus:ring-red-500 dark:bg-gray-700 focus:border-red-500 block w-full p-2.5 dark:text-red-500 dark:placeholder-red-500 dark:border-red-500" : "bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"}
                                   placeholder="JohnDoe"/>
                            {errors.username && (
                              <p className="mt-2 text-sm text-red-600 dark:text-red-500">{errors.username.message}</p>)}
                          </div>
                          <div>
                            <label htmlFor="password"
                                   className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
                              Mot de passe
                            </label>
                            <input type="password"
                                   name="password"
                                   id="password"
                                   {...register("password", {required: "Le mot de passe est requis", minLength: 8})}
                                   className={errors.password ? "bg-red-50 border border-red-500 text-red-900 placeholder-red-700 text-sm rounded-lg focus:ring-red-500 dark:bg-gray-700 focus:border-red-500 block w-full p-2.5 dark:text-red-500 dark:placeholder-red-500 dark:border-red-500" : "bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"}
                                   placeholder=""/>
                            {errors.password && errors.password.type !== "minLength" && (
                              <p className="mt-2 text-sm text-red-600 dark:text-red-500">{errors.password.message}</p>)}
                            {errors.password && errors.password.type === "minLength" && (
                              <p className="mt-2 text-sm text-red-600 dark:text-red-500">Le mot de passe doit avoir une
                                longueur minimum de 8 charactères</p>)}
                          </div>
                          <div>
                            <label htmlFor="passwordConfirmation"
                                   className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
                              Confirmez le mot de passe
                            </label>
                            <input type="password"
                                   name="passwordConfirmation"
                                   id="passwordConfirmation"
                                   {...register("passwordConfirmation", {
                                     required: "Veuillez confirmer le mot de passe", validate: {
                                       matchesPreviousPassword: (value) => {
                                         const {password} = getValues();
                                         return password === value || "Les mots de passe ne correspondent pas";
                                       }
                                     }
                                   })}
                                   className={errors.passwordConfirmation ? "bg-red-50 border border-red-500 text-red-900 placeholder-red-700 text-sm rounded-lg focus:ring-red-500 dark:bg-gray-700 focus:border-red-500 block w-full p-2.5 dark:text-red-500 dark:placeholder-red-500 dark:border-red-500" : "bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"}
                                   placeholder=""/>
                            {errors.passwordConfirmation && (
                              <p
                                className="mt-2 text-sm text-red-600 dark:text-red-500">{errors.passwordConfirmation.message}</p>)}
                          </div>
                        </section>
                        <section className="py-5">
                          <div className="flex items-center">
                            <input id="agreement"
                                   type="checkbox"
                                   value=""
                                   name="agreement"
                                   {...register("agreement", {required: "Vous devez accepter les conditions d'utilisation"})}
                                   className="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-blue-600 dark:ring-offset-gray-800 dark:focus:ring-offset-gray-800"/>
                            <label htmlFor="agreement"
                                   className="ml-2 text-sm font-medium text-gray-900 dark:text-gray-300">
                              En vous inscrivant, vous créez un compte MeCP et vous acceptez les conditions
                              d&apos;utilisation et la politique de confidentialité de MeCP.
                            </label>
                          </div>
                          {errors.agreement && (
                            <p className="mt-2 text-sm text-red-600 dark:text-red-500">{errors.agreement.message}</p>)}
                        </section>
                        <section className="flex items-center pb-5">
                          <input id="newsletter"
                                 type="checkbox"
                                 value=""
                                 name="newsletter"
                                 {...register("newsletter")}
                                 className="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-blue-600 dark:ring-offset-gray-800 dark:focus:ring-offset-gray-800"/>
                          <label htmlFor="newsletter"
                                 className="ml-2 text-sm font-medium text-gray-900 dark:text-gray-300">
                            Envoyez-moi un e-mail sur les mises à jour de l&apos;école, des cours et les produits.
                          </label>
                        </section>
                        <section className="flex items-center pt-5">
                          <button type="submit"
                                  className="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 mr-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800 w-full disabled:bg-gray-500 focus:disabled:bg-gray-500 hover:disabled:bg-gray-500"
                                  data-mdb-ripple="true"
                                  data-mdb-ripple-color="light" disabled={hasErrors()}>
                            Inscription
                          </button>
                        </section>
                      </main>
                    </form>
                  </div>
                </div>
                <div className="md:w-8/12 lg:w-6/12 mb-12 md:mb-0 hidden md:block">
                  <img src="https://mdbcdn.b-cdn.net/img/Photos/new-templates/bootstrap-login-form/draw2.png"
                       className="w-full" alt="Phone image"/>
                </div>
              </div>
            </div>
          </section>
        </div>
      </Layout>
    </>
  );
}

export default SignUp;
