"use client";

import { useEffect, useState } from "react";
import { FaChevronRight } from "react-icons/fa6";
import { useRouter, useSearchParams } from "next/navigation";
import { useFormState, useFormStatus } from "react-dom";

import StepHeading from "@/components/pages/participant/sign-up/common/step-heading";
import Button from "@/components/common/button";
import { verifyOTP } from "@/services/global/request-sms-otp-actions";
import Alert from "@/components/common/alert";
import { INTERNAL_PAGES } from "@/constants/pages-mapping/internal-pages-mapping";
import OTPDigits from "@/components/common/otp-digits";

type VerifyAccountProps = {
  phoneNumber?: string;
};

function SubmitButton() {
  const { pending } = useFormStatus();

  return (
    <Button
      fullWidth
      aria-disabled={pending}
      btnLabel={pending ? "Verifying your code..." : "Continue to next step"}
      className="mt-12"
      customVariant="black"
      endContent={pending ? null : <FaChevronRight />}
      isDisabled={pending}
      isLoading={pending}
      type="submit"
    />
  );
}

function VerifyAccount({ phoneNumber }: VerifyAccountProps) {
  const router = useRouter();
  const [, setOTPCode] = useState<string>("");
  const searchParams = useSearchParams();
  const queryString = searchParams.toString();

  const [state, formAction] = useFormState(verifyOTP, {
    success: false,
    errorCode: "",
    error: "",
  });

  useEffect(() => {
    if (state.success) {
      queryString
        ? router.push(
            `${INTERNAL_PAGES.participant.signup.userInformation}?${queryString}`,
          )
        : router.push(INTERNAL_PAGES.participant.signup.userInformation);
    }
  }, [queryString, router, state.success]);

  return (
    <main
      className="xl:w-7/12 relative bg-white xl:pt-0 pt-12 light pb-12"
      id="main-content"
    >
      <div className="absolute xl:hidden top-0 w-full h-2 bg-participant-bittersweet dark:bg-participant-cerulean" />
      <StepHeading
        currentStep={2}
        subtitle="Confirm your identity with a secure SMS code."
        title="Verify your mobile number"
      />
      <form
        noValidate
        action={formAction}
        className="xl:mx-16 my-8 items-center justify-center flex flex-col space-y-4"
      >
        <OTPDigits
          showDefaultIntroText
          allowSendNewCode={false}
          parsedPhoneNumber={phoneNumber}
          sendNewCodeBtnEnabled={false}
          onChange={(value: string) => {
            setOTPCode(value);
          }}
          onSendNewCode={() => {}}
        />
        {state.errors && (
          <Alert
            message="The SMS code might be missing or incorrect. Please double-check the digits and try again."
            title="Error"
            variant="alert"
          />
        )}
        {state.error && (
          <Alert
            message={state.error}
            title={`Error (${state.errorCode})`}
            variant="error"
          />
        )}
        <SubmitButton />
      </form>
    </main>
  );
}

export default VerifyAccount;
