"use client";

import { FaChevronRight } from "react-icons/fa6";
import { Controller, useForm } from "react-hook-form";
import { useSearchParams, 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 PFRDefaultLogo from "@/components/common/sprites/pfr-default-logo-sprite";
import Breadcrumbs from "@/components/common/breadcrumbs";
import PasswordInput from "@/components/common/password-input";
import { AUTOCOMPLETE_VALUES } from "@/constants/signup-auto-complete-mapping";
import { INTERNAL_PAGES } from "@/constants/pages-mapping/internal-pages-mapping";
import Alert from "@/components/common/alert";
import { resetPassword } from "@/services/participant/reset-password/reset-pwd-actions";
import FormError from "@/components/common/form-error";

type ResetPasswordForm = {
  password: string;
  confirmPassword: string;
};

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

  const getButtonLabel = () => {
    if (pending) return "Loading...";
    if (!isTurnstileReady) return "Waiting for security verification...";
    return "Reset my password";
  };

  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 ResetPassword() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const turnstileRef = useRef<TurnstileInstance>(null);
  const token = searchParams.get("token") as string;
  let email = searchParams.get("email") || "";
  email = decodeURIComponent(email.replace(/\s/g, "+")); // this is necessary to support special chars like + in email
  const turnstileSiteKey = process.env
    .NEXT_PUBLIC_CLOUDFLARE_TURNSTILE_SITE_KEY as string;
  const isTurnstileReady = !!turnstileRef.current?.getResponse();
  const [turnstileToken, setTurnstileToken] = useState<string>();

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

  const { control } = useForm<ResetPasswordForm>({
    defaultValues: {
      password: "",
      confirmPassword: "",
    },
    mode: "all",
  });

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

  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-24 xl:mt-0 text-black space-y-6 px-12 xl:mx-12">
        <h1 className="font-inter font-black text-4xl text-center">
          Reset your password
        </h1>
        <h2 className="font-noto text-base text-center">
          Please choose a new password for the email{" "}
          <kbd className="px-2 py-1 text-xs text-gray-900 bg-gray-100 border border-gray-300 rounded-md">
            {email}
          </kbd>{" "}
          and enter it below. Once you&apos;ve updated it here, you&apos;ll
          receive an email to confirm the change.
        </h2>
      </div>
      <form
        noValidate
        action={formAction}
        className="px-12 xl:px-24 flex flex-col gap-4 my-6 mt-16"
      >
        <Controller
          control={control}
          name="password"
          render={({ fieldState, field }) => {
            return (
              <PasswordInput
                control={control}
                fieldProps={field}
                fieldState={fieldState}
                label="New password"
                name={field.name}
                placeholder="Your new password"
              />
            );
          }}
        />
        {state.errors?.password && <FormError text={state.errors.password} />}
        <Controller
          control={control}
          name="confirmPassword"
          render={({ fieldState, field }) => {
            return (
              <PasswordInput
                autoComplete={AUTOCOMPLETE_VALUES.NEW_PASSWORD}
                control={control}
                fieldProps={field}
                fieldState={fieldState}
                label="Confirm new password"
                name={field.name}
                placeholder="Confirm new password"
                showGuidelines={false}
              />
            );
          }}
        />
        {state.errors?.confirmPassword && (
          <FormError text={state.errors.confirmPassword} />
        )}
        <Turnstile
          ref={turnstileRef}
          as="aside"
          options={{
            action: "reset-password",
            theme: "light",
            size: "flexible",
          }}
          siteKey={turnstileSiteKey}
          onSuccess={(token) => setTurnstileToken(token)}
        />
        {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"
          />
        )}
        {state.success && (
          <Alert
            message="Your password has been successfully updated. Please log in with your new password."
            title="Success"
            variant="success"
          />
        )}
        {state.success && (
          <Button
            btnLabel="Log in"
            customVariant="primary"
            endContent={<FaChevronRight />}
            onClick={() => router.push(INTERNAL_PAGES.participant.login)}
          />
        )}
        {!state.success && <SubmitButton isTurnstileReady={isTurnstileReady} />}
      </form>
    </main>
  );
}

export default ResetPassword;
