"use client";

import { FaChevronRight, FaUserLock } from "react-icons/fa6";
import { Controller, useForm } from "react-hook-form";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { Turnstile, TurnstileInstance } from "@marsidev/react-turnstile";
import { useFormState, useFormStatus } from "react-dom";

import Button from "@/components/common/button";
import { AUTOCOMPLETE_VALUES } from "@/constants/signup-auto-complete-mapping";
import { INTERNAL_PAGES } from "@/constants/pages-mapping/internal-pages-mapping";
import PFRDefaultLogo from "@/components/common/sprites/pfr-default-logo-sprite";
import Breadcrumbs from "@/components/common/breadcrumbs";
import TextInput from "@/components/common/text-input";
import Alert from "@/components/common/alert";
import { requestNewPassword } from "@/services/participant/forgot-password/forgot-pwd-actions";
import FormError from "@/components/common/form-error";

export type ForgotPasswordForm = {
  email: string;
};

function SubmitButton({ isTurnstileReady }: { isTurnstileReady: boolean }) {
  const { pending } = useFormStatus();

  const getButtonLabel = () => {
    if (pending) return "Sending email...";
    if (!isTurnstileReady) return "Waiting for security verification...";
    return "Send reset email";
  };

  return (
    <Button
      fullWidth
      aria-disabled={pending || !isTurnstileReady}
      btnLabel={getButtonLabel()}
      className="bg-saffron mt-12 m-auto"
      customVariant="black"
      endContent={pending || !isTurnstileReady ? null : <FaChevronRight />}
      isDisabled={pending || !isTurnstileReady}
      isLoading={pending}
      type="submit"
    />
  );
}

function ForgotPassword() {
  const router = useRouter();
  const turnstileRef = useRef<TurnstileInstance>(null);
  const isTurnstileReady = !!turnstileRef.current?.getResponse();
  const turnstileSiteKey = process.env
    .NEXT_PUBLIC_CLOUDFLARE_TURNSTILE_SITE_KEY as string;
  const [token, setToken] = useState<string>();

  const { control } = useForm<ForgotPasswordForm>({
    defaultValues: {
      email: "",
    },
    mode: "all",
  });

  const [state, formAction] = useFormState(
    requestNewPassword.bind(null, token),
    {
      success: false,
      error: "",
    }
  );

  useEffect(() => {
    if (!state.success) {
      turnstileRef.current?.reset();
    }
  }, [state]);

  const handleClickLogin = () => {
    router.push(INTERNAL_PAGES.participant.login);
  };

  return (
    <main
      className="xl:w-1/2 relative bg-white xl:pt-0 py-12 light"
      id="main-content"
    >
      <div className="absolute xl:hidden top-0 w-full h-2 bg-participant-bittersweet dark:bg-participant-cerulean" />
      <div className="xl:hidden flex items-center justify-center">
        <Breadcrumbs />
      </div>
      <div className="hidden xl:flex items-center justify-center mt-0 xl:mt-16">
        <PFRDefaultLogo fill="text-black" width={150} />
      </div>
      <div className="text-center mt-12 xl:mt-0 text-black space-y-6 px-12 xl:mx-12">
        <h1 className="font-inter font-black text-4xl text-center">
          Forgot your password? We got you.
        </h1>
        <h2 className="font-noto text-base text-center">
          Enter the email address you used to create your People for Research
          account. We&apos;ll send you a password reset email.
        </h2>
      </div>
      <form
        noValidate
        action={formAction}
        className="px-12 xl:px-24 space-y-4 mt-16"
      >
        <Controller
          control={control}
          name="email"
          render={({ fieldState, field }) => {
            return (
              <TextInput
                autoComplete={AUTOCOMPLETE_VALUES.EMAIL}
                control={control}
                description="We'll send you an email with a link, which you can use to reset your password."
                fieldProps={field}
                fieldState={fieldState}
                label="Email address"
                name={field.name}
                placeholder="Your email address"
              />
            );
          }}
        />
        {state.errors?.email && <FormError text={state.errors.email} />}
        <Turnstile
          ref={turnstileRef}
          as="aside"
          options={{
            action: "forgot-password",
            theme: "light",
            size: "flexible",
          }}
          siteKey={turnstileSiteKey}
          onSuccess={(token) => setToken(token)}
        />
        {state.success && (
          <Alert
            message="We have sent you an email with a link to reset your password."
            title="Success"
            variant="success"
          />
        )}
        {state.error && (
          <Alert
            message={state.error}
            title={`Error (${state.errorCode})`}
            variant="error"
          />
        )}
        {state.errors && (
          <Alert
            message="Some fields have missing or incorrect information. Please review the highlighted fields and correct any errors."
            title="Error"
            variant="alert"
          />
        )}
        <SubmitButton isTurnstileReady={isTurnstileReady} />
        <Button
          fullWidth
          btnLabel="Login"
          customVariant="transparent-black"
          startContent={<FaUserLock />}
          onClick={handleClickLogin}
        />
      </form>
      <div className="flex flex-row font-noto font-medium text-sm text-center items-center justify-center pt-8 text-black">
        <span className="block font-noto font-medium text-sm text-center">
          New to People for Research?
        </span>
        <Link
          className="ms-1 underline underline-offset-2 decoration-dotted cursor-pointer font-bold"
          href={INTERNAL_PAGES.participant.signup.main}
        >
          Create a new account
        </Link>
        .
      </div>
    </main>
  );
}

export default ForgotPassword;
