"use client";

import { Controller, useForm } from "react-hook-form";
import { useRouter, useSearchParams } from "next/navigation";
import { FaCircleCheck } from "react-icons/fa6";
import { useEffect } from "react";
import { useFormState, useFormStatus } from "react-dom";

import SecondaryHeading from "@/components/pages/participant/sign-up/common/secondary-heading";
import StepHeading from "@/components/pages/participant/sign-up/common/step-heading";
import Button from "@/components/common/button";
import { Options } from "@/types/options/options-data-types";
import TermsAndConditions from "@/components/pages/participant/sign-up/common/terms-conditions";
import { EmploymentStatusData } from "@/types/signup/user-signup-types";
import CompanyContactsFooter from "@/components/pages/participant/sign-up/common/company-contacts-footer";
import TextInput from "@/components/common/text-input";
import Select from "@/components/common/select";
import { validateEmploymentInformation } from "@/services/participant/signup/signup-employment-information-actions";
import { INTERNAL_PAGES } from "@/constants/pages-mapping/internal-pages-mapping";
import FormError from "@/components/common/form-error";
import Alert from "@/components/common/alert";

type EmploymentInformationProps = {
  seniorityOptions: Options;
  industryOptions: Options;
  userFirstName: string;
};

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

  return (
    <Button
      fullWidth
      aria-disabled={pending}
      btnLabel={pending ? "Validating your data..." : "Finish registration"}
      customVariant="black"
      endContent={pending ? null : <FaCircleCheck />}
      isDisabled={pending}
      isLoading={pending}
      type="submit"
    />
  );
}

function EmploymentInformation({
  seniorityOptions,
  industryOptions,
  userFirstName,
}: EmploymentInformationProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const queryString = searchParams.toString();
  const userSource = searchParams.get("utm_source") || undefined;

  const { control } = useForm<EmploymentStatusData>({
    mode: "all",
    defaultValues: {
      occupation: "",
      seniorityLevel: [],
      industryId: 0,
    },
  });

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

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

  return (
    <main
      className="xl:w-7/12 relative bg-white xl:pt-0 pt-12 light pb-10"
      id="main-content"
    >
      <div className="absolute xl:hidden top-0 w-full h-2 bg-participant-bittersweet dark:bg-participant-cerulean" />
      <StepHeading
        currentStep={5}
        subtitle={`Nearly there, ${userFirstName}! Just a few more questions about you.`}
        title="Finish account set up"
      />
      <div className="flex flex-col flex-grow">
        <div className="mt-6 space-y-0 ms-6 xl:ms-16">
          <SecondaryHeading title="About your employment" />
          <p className="font-noto text-xs text-others-shadowGray">
            Please enter your current employment information below.
          </p>
        </div>
        <form
          noValidate
          action={formAction}
          className="mt-6 sm:mt-8 flex flex-col gap-4 xl:mx-16 mx-6"
        >
          <Controller
            control={control}
            name="occupation"
            render={({ fieldState, field }) => {
              return (
                <TextInput
                  isClearable
                  control={control}
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Job title"
                  name={field.name}
                  placeholder="Your current job title"
                />
              );
            }}
          />
          {state.errors?.occupation && (
            <FormError text={state.errors.occupation} />
          )}
          <Controller
            control={control}
            name="seniorityLevel"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={seniorityOptions}
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Seniority level"
                  name={field.name}
                  placeholder="Select your seniority level"
                  selectionMode="multiple"
                />
              );
            }}
          />
          {state.errors?.seniorityLevel && (
            <FormError text={state.errors.seniorityLevel} />
          )}
          <Controller
            control={control}
            name="industryId"
            render={({ field, fieldState }) => {
              return (
                <Select
                  control={control}
                  data={industryOptions}
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Your industry"
                  name={field.name}
                  placeholder="Select your industry"
                />
              );
            }}
          />
          {state.errors?.industryId && (
            <FormError text={state.errors.industryId} />
          )}
          {state.error && (
            <Alert
              showSupportEmail
              message="An error has occurred while trying to create your account. Please try again. If the error persists, please contact us at "
              title="Error"
              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 />
        </form>
      </div>
      <div className="mt-16 mb-10 mx-8 sm:mb-4 sm:mx-28 lg:mb-3 lg:mx-0 space-y-6">
        <TermsAndConditions />
        <CompanyContactsFooter />
      </div>
    </main>
  );
}

export default EmploymentInformation;
