"use client";

import { FaCheck, FaChevronRight } from "react-icons/fa6";
import { Controller, useForm } from "react-hook-form";
import { useEffect, useState } from "react";
import { parsePhoneNumber } from "awesome-phonenumber";
import { useFormState, useFormStatus } from "react-dom";
import { useRouter } from "next/navigation";

import { ManualPhoneVerification } from "@/types/profile/profile-update-schema";
import Button from "@/components/common/button";
import ProgressBar from "@/components/common/progress-bar";
import Breadcrumbs from "@/components/common/breadcrumbs";
import TextInput from "@/components/common/text-input";
import { firstStepManualPhoneVerification } from "@/services/participant/profile/manual-phone-verification-actions";
import { INTERNAL_PAGES } from "@/constants/pages-mapping/internal-pages-mapping";
import { verifyOTPManualPhoneVerification } from "@/services/global/request-sms-otp-actions";
import Alert from "@/components/common/alert";
import FormError from "@/components/common/form-error";
import OTPDigits from "@/components/common/otp-digits";

type ManuelPhoneVerificationProps = {
  userFirstName: string;
  userCountryCode: string;
  currentPhoneNumber: string;
  isVerified: boolean;
  userEmail: string;
};

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

  return (
    <Button
      fullWidth
      btnLabel={pending ? "Requesting code..." : "Continue to next step"}
      customVariant="black"
      endContent={<FaChevronRight />}
      isLoading={pending}
      type="submit"
    />
  );
}

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

  return (
    <Button
      fullWidth
      aria-disabled={pending}
      btnLabel={pending ? "Verifying code..." : "Verify my new phone number"}
      customVariant="black"
      endContent={<FaCheck />}
      isDisabled={pending}
      isLoading={pending}
      type="submit"
    />
  );
}

function ManualPhoneVerificationProcess({
  userFirstName,
  currentPhoneNumber,
  isVerified,
  userEmail,
  userCountryCode,
}: ManuelPhoneVerificationProps) {
  const router = useRouter();
  const [currentStep, setCurrentStep] = useState(1);
  const [, setOtpCode] = useState("");

  const { control, getValues } = useForm<ManualPhoneVerification>({
    defaultValues: {
      phoneNumber: `${userCountryCode}`,
      verificationCode: undefined,
    },
    mode: "all",
  });

  const newPhoneNumber = getValues("phoneNumber");

  const [firstStepState, formActionFirstStep] = useFormState(
    firstStepManualPhoneVerification.bind(null, currentPhoneNumber),
    {
      success: false,
      error: "",
    }
  );

  const [secondStepState, formActionSecondStep] = useFormState(
    verifyOTPManualPhoneVerification.bind(null, newPhoneNumber, userEmail),
    {
      success: false,
      errorCode: "",
      error: "",
    }
  );

  useEffect(() => {
    if (firstStepState.success) {
      setCurrentStep(2);
    }
  }, [firstStepState.success]);

  useEffect(() => {
    if (secondStepState.success) {
      router.push(INTERNAL_PAGES.participant.profile.contactInfo);
    }
  }, [router, secondStepState.success]);

  return (
    <div className="mb-24">
      <div className="block lg:hidden m-4">
        <Breadcrumbs />
      </div>
      <div className="bg-white p-8 rounded-md m-4 sm:m-20 lg:m-auto mt-4 lg:w-1/2 lg:h-1/2 lg:mt-12">
        <ProgressBar
          className="mb-8"
          classNames={{
            label: "text-sm font-bold text-black tracking-tight font-inter",
            indicator:
              "bg-gradient-to-r dark:from-paleBlue dark:to-participant-cerulean from-peach to-participant-bittersweet",
          }}
          label={`Your mobile number verification process (${currentStep}/2)`}
          maxValue={2}
          minValue={1}
          value={currentStep === 2 ? currentStep - 0.2 : currentStep + 0.1}
        />
        {currentStep === 1 && (
          <div className="mt-4 space-y-4 text-black">
            <h1 className="font-inter text-xl font-extrabold tracking-tight">
              {isVerified
                ? "Change mobile number"
                : "Mobile number verification"}
            </h1>
            <p className="font-noto text-base">
              {isVerified
                ? `${userFirstName}, your mobile number (${
                    parsePhoneNumber(currentPhoneNumber).number?.international
                  }) is currently verified. This process allows you to change your mobile number and re-verify your identity.`
                : `${userFirstName}, verify your mobile number so we can
              validate your account. Having your account verified allows People
              for Research to verify your identity and boosts your chances of
              being selected to be part of a study with us.`}
            </p>
            <p className="font-noto text-base">
              {isVerified
                ? "Please add your new mobile number below. A verification code will be sent to your new mobile number."
                : "Please add or update your mobile number below. You can edit your number below if it's no longer up-to-date."}
            </p>
            <form action={formActionFirstStep} className="flex flex-col gap-4">
              <Controller
                control={control}
                name="phoneNumber"
                render={({ fieldState, field }) => {
                  return (
                    <TextInput
                      isClearable
                      control={control}
                      description="The country code (e.g. +44) is required. Your phone number is required to verify your identify."
                      fieldProps={field}
                      fieldState={fieldState}
                      label="Your new phone number"
                      name={field.name}
                      placeholder="Your new phone number"
                    />
                  );
                }}
              />
              {firstStepState.errors?.phoneNumber && (
                <FormError text={firstStepState.errors.phoneNumber} />
              )}
              {firstStepState.error && (
                <Alert
                  message={firstStepState.error}
                  title={`Error (${firstStepState.errorCode})`}
                  variant="error"
                />
              )}
              <MoveNextStep />
            </form>
          </div>
        )}

        {currentStep === 2 && (
          <div className="mt-4 space-y-4 text-black">
            <h1 className="font-inter text-xl font-extrabold tracking-tight">
              Mobile number verification
            </h1>
            <p className="font-noto text-base mt-4">
              {userFirstName}, a verification code was sent to the new mobile
              number you provided:{" "}
              {parsePhoneNumber(newPhoneNumber).number?.international}.
            </p>
            <p className="font-noto text-base mt-4">
              Input the code you received by text message below. Please allow up
              to 2 minutes for the code to arrive.
            </p>
            <form
              noValidate
              action={formActionSecondStep}
              className="xl:mx-16 my-8 space-y-4"
            >
              <OTPDigits
                showDefaultIntroText
                allowSendNewCode={false}
                parsedPhoneNumber={newPhoneNumber}
                sendNewCodeBtnEnabled={false}
                onChange={(value: string) => {
                  setOtpCode(value);
                }}
                onSendNewCode={() => {}}
              />
              {secondStepState.error && (
                <Alert
                  message={secondStepState.error}
                  title="Error"
                  variant="error"
                />
              )}

              <SubmitForm />
            </form>
          </div>
        )}
      </div>
    </div>
  );
}

export default ManualPhoneVerificationProcess;
