import delve from "dlv";
import axios from "axios";
import {SubmitHandler, useForm} from "react-hook-form";

import SeoConfig from "../../components/seo-config/seo-config";
import Layout from "../../components/layout/layout";
import {environment} from "../../environments/environment";
import {ResetPasswordInputs} from "../../libs/api";

import styles from './index.module.scss';
import {useRouter} from "next/router";
import {useState} from "react";
import {resetPasswordStrapi} from "../../libs/auth";

const getPageMetadata = async (path) => {
  try {
    return await axios.get(`${environment.strapiApiUrl}/pages?filters[slug]=${path === '/' ? 'home' : path.slice(1, path.length)}&populate=deep`);
  } catch (e) {
    console.error(e);
    return Promise.resolve({})
  }
}

export const getServerSideProps = async (context) => {
  const path = context.resolvedUrl;
  const menuHeader = await axios.get(`${environment.strapiApiUrl}/menus/1?nested&populate=deep`);
  const menuFooter = await axios.get(`${environment.strapiApiUrl}/menus/2?nested&populate=deep`);
  const page = await getPageMetadata(path);
  return {
    props: {
      menuHeaders: delve(menuHeader, 'data.data.attributes.items.data', []),
      menuFooter: delve(menuFooter, 'data.data.attributes.items.data', []),
      page: delve(page, "data.data.0.attributes", {}),
      seo: delve(page, "data.data.0.attributes.seo", {})
    }
  }
}

export function ResetPassword({menuHeaders, menuFooter, page, seo}) {
  const router = useRouter();
  const [success, setSuccess] = useState(null);

  const {register, handleSubmit, getValues, formState: {errors}} = useForm({
    defaultValues: {
      password: null,
      passwordConfirmation: null,
      code: router.query ? router.query.code : null
    }
  });

  const onSubmit: SubmitHandler<ResetPasswordInputs> = async (data: ResetPasswordInputs) => {
    try {
      const result = await resetPasswordStrapi({
        password: data.password,
        passwordConfirmation: data.passwordConfirmation,
        code: data.code
      });
      setSuccess(result);
      setTimeout(() => router.push('/sign-in'), 5000);
    } catch (e) {
      setSuccess(false);
    }
  }

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

  const isBoolean = (val) => typeof val === "boolean";

  return (
    <>
      <SeoConfig {...seo}/>
      <Layout menuHeader={menuHeaders} 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 mb-12 md:mb-0 hidden md:block">
                  <img src="/images/page-lost-password.png"
                       className="w-full" alt="Phone image"/>
                </div>
                <div className="md:w-8/12 lg:w-6/12 flex justify-end">
                  <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">Changer votre mot de passe</h3>
                        <p className="mb-6 text-base font-normal text-gray-500 dark:text-gray-400">
                          Indiquez votre nouveau mot de passe
                        </p>
                      </header>
                      {isBoolean(success) && success ? (<div
                        className="p-4 mb-4 text-sm text-green-800 rounded-lg bg-green-50 dark:bg-gray-800 dark:text-green-400"
                        role="alert">
                        <span className="font-medium">Mot de passe changé !</span> vous allez être redirigé vers la page
                        de connexion.
                      </div>) : ('')}
                      {isBoolean(success) && !success ? (<div
                        className="p-4 mb-4 text-sm text-red-800 rounded-lg bg-red-50 dark:bg-gray-800 dark:text-red-400"
                        role="alert">
                        <span className="font-medium">Oups !</span> Une erreur est survenue durant le changement du mot
                        de passe. Rapprochez vous de nos équipes pour en savoir plus.
                      </div>) : ('')}
                      <main>
                        <section className="grid grid-cols-1 gap-4 mb-4">
                          <div>
                            <label htmlFor="password"
                                   className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
                              Mot de passe
                            </label>
                            <div className="relative">
                              <input type="password"
                                     name="password"
                                     id="password"
                                     {...register("password", {required: "Le mot de passe est requis", minLength: 8})}
                                     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'}/>
                              {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>
                          <div>
                            <label htmlFor="passwordConfirmation"
                                   className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
                              Confirmez votre mot de passe
                            </label>
                            <div className="relative">
                              <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.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 pr-10 p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white'}/>
                              {errors.passwordConfirmation && (
                                <p
                                  className="mt-2 text-sm text-red-600 dark:text-red-500">{errors.passwordConfirmation.message}</p>)}
                            </div>
                          </div>
                        </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 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()}>
                            Changer votre mot de passe
                          </button>
                        </section>
                      </main>
                    </form>
                  </div>
                </div>
              </div>
            </div>
          </section>
        </div>
      </Layout>
    </>
  );
}

export default ResetPassword;
