"use client";

import { FaChevronRight, FaLock, FaUserPlus } 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 PasswordInput from "@/components/common/password-input";
import Alert from "@/components/common/alert";
import { userLogin } from "@/services/participant/login/login-actions";
import FormError from "@/components/common/form-error";

type UserLogin = {
  email: string;
  password: string;
};

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

  const getButtonLabel = () => {
    if (pending) return "Logging in...";
    if (!isTurnstileReady) return "Waiting for security verification...";
    return "Log in";
  };

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

type LoginProps = {
  email?: string;
  jobIdRef?: string;
  emailUpdated?: string;
  utmParams?: Record<string, string>;
};

function Login({ email, jobIdRef, emailUpdated, utmParams }: LoginProps) {
  const router = useRouter();
  const isChangeEmailProcess = emailUpdated && email;

  const utmString = new URLSearchParams(utmParams ?? {}).toString();

  const handleJoinCommunity = () => {
    const params = new URLSearchParams();

    if (jobIdRef) params.set("jobIdRef", jobIdRef);

    Object.entries(utmParams ?? {}).forEach(([key, value]) => {
      params.set(key, value);
    });

    const queryString = params.toString();

    router.push(
      queryString
        ? `${INTERNAL_PAGES.participant.signup.main}?${queryString}`
        : INTERNAL_PAGES.participant.signup.main,
    );
  };

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

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

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

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

    if (state.success) {
      // redirects to survey if jobIdRef exists, otherwise go to profile. asked by dops - Nov 25.
      const surveyUrl = jobIdRef
        ? `${INTERNAL_PAGES.participant.opportunities.main}/${jobIdRef}/survey`
        : INTERNAL_PAGES.participant.profile.main;

      const destination =
        jobIdRef && utmString ? `${surveyUrl}?${utmString}` : surveyUrl;

      router.push(destination);
    }
  }, [state, router, jobIdRef, utmString]);

  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-8 xl:mt-0 mx-8 xl:mx-12 text-black space-y-4">
        <h1 className="font-inter font-black text-4xl text-center">
          Welcome back.
        </h1>
        <h2 className="font-noto text-base text-center">
          Please enter your email and password in order to log in.
        </h2>
      </div>
      <form
        noValidate
        action={formAction}
        className="px-12 xl:px-24 flex flex-col gap-4 mt-12"
      >
        <Controller
          control={control}
          name="email"
          render={({ fieldState, field }) => {
            return (
              <TextInput
                isClearable
                autoComplete={AUTOCOMPLETE_VALUES.EMAIL}
                control={control}
                fieldProps={field}
                fieldState={fieldState}
                label="Email address"
                name={field.name}
                placeholder="Your email address"
              />
            );
          }}
        />
        {state.errors?.email && <FormError text={state.errors.email} />}
        <Controller
          control={control}
          name="password"
          render={({ fieldState, field }) => {
            return (
              <PasswordInput
                isClearable
                control={control}
                fieldProps={field}
                fieldState={fieldState}
                label="Password"
                name={field.name}
                placeholder="Your password"
                showGuidelines={false}
                startContent={<FaLock />}
              />
            );
          }}
        />
        {state.errors?.password && <FormError text={state.errors.password} />}
        <Turnstile
          ref={turnstileRef}
          as="aside"
          options={{
            action: "login",
            theme: "light",
            size: "flexible",
          }}
          siteKey={turnstileSiteKey}
          onSuccess={(token) => setToken(token)}
        />
        {state.error && (
          <Alert
            message={state.error}
            title={`Error (${state.errorCode})`}
            variant="error"
          />
        )}
        {isChangeEmailProcess && (
          <Alert
            message="Your email has been changed successfully. Please re-login with your new email."
            title="Email changed successfully"
            variant="success"
          />
        )}
        {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
          btnLabel="Join our community"
          customVariant="transparent-black"
          startContent={<FaUserPlus />}
          onClick={handleJoinCommunity}
        />
      </form>
      <div className="flex flex-row font-noto font-medium text-sm text-center items-center justify-center pt-8 text-black">
        <Link
          className="ms-1 underline underline-offset-2 decoration-dotted cursor-pointer font-bold"
          href={INTERNAL_PAGES.participant.forgotPassword}
        >
          Forgot your password?
        </Link>
      </div>
    </main>
  );
}

export default Login;
