import axios from "axios";
import delve from "dlv";
import {useState} from "react";
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 {LostPasswordInputs} from "../../libs/api";
import {lostPasswordStrapi} from "../../libs/auth";

import styles from "../sign-up/index.module.scss";

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 LostPassword({menuHeaders, menuFooter, page, seo}) {
  const {register, handleSubmit, formState: {errors}} = useForm({
    defaultValues: {
      email: ""
    }
  });
  const [isSent, setIsSent] = useState(null);

  const onSubmit: SubmitHandler<LostPasswordInputs> = async (data: LostPasswordInputs) => {
    try {
      const result = await lostPasswordStrapi({email: data.email});
      setIsSent(result);
    } catch (e) {
      setIsSent(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">
                  <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">Mot de passe oublié</h3>
                        <p className="mb-6 text-base font-normal text-gray-500 dark:text-gray-400">
                          Veuillez saisir votre addresse email ci-dessous et nous vous enverrons un courriel pour
                          changer votre mot de passe.
                        </p>
                      </header>
                      <main>
                        {isBoolean(isSent) && isSent ? (<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">Email envoyé !</span> Vérifiez votre boite de réception ou vos
                          courrier indésirables.
                        </div>) : ('')}
                        {isBoolean(isSent) && !isSent ? (<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 l'envoi de l'email.
                          Rapprochez vous de nos équipes pour en savoir plus.
                        </div>) : ('')}
                        <section className="grid grid-cols-1 gap-4 mb-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">
                              <input type="email"
                                     name="email"
                                     id="email"
                                     {...register("email", {required: "L'email est requis"})}
                                     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>
                        </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()}>
                            Envoyer le code par email
                          </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="/images/page-lost-password.png"
                       className="w-full" alt="Phone image"/>
                </div>
              </div>
            </div>
          </section>
        </div>
      </Layout>
    </>
  );
}

export default LostPassword;
