"use client";

import { useForm, Controller } from "react-hook-form";
import { FaSave } from "react-icons/fa";
import { useFormState, useFormStatus } from "react-dom";

import ProfileLayout from "@/components/pages/participant/profile/partials/profile-layout";
import { Options } from "@/types/options/options-data-types";
import { FinancialEmploymentProfileSchema } from "@/types/profile/profile-update-schema";
import Select from "@/components/common/select";
import Button from "@/components/common/button";
import TextInput from "@/components/common/text-input";
import { getCurrencyIdFromCountry } from "@/utils/map-currency-profile";
import { updateFinancialEmployment } from "@/services/participant/profile/update-financial-employment-actions";
import Alert from "@/components/common/alert";
import FormError from "@/components/common/form-error";

type FinancialInfoTabProps = {
  options: {
    financialProducts: Options;
    seniorityLevelIds: Options;
    benefits: Options;
    industry: Options;
    employmentStatusIds: Options;
    individualIncome: Options;
  };
  profileData: FinancialEmploymentProfileSchema;
  userCountryId: number;
  userId: number;
};

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

  return (
    <Button
      fullWidth
      aria-disabled={pending}
      btnLabel={pending ? "Saving data..." : "Save my profile"}
      className="mt-4"
      customVariant="black"
      isDisabled={pending}
      isLoading={pending}
      startContent={pending ? null : <FaSave />}
      type="submit"
    />
  );
}

function FinancialEmployment({
  options: {
    financialProducts: financialOptions,
    seniorityLevelIds: seniorityOptions,
    benefits: benefitOptions,
    industry: industryOptions,
    employmentStatusIds: employmentOptions,
    individualIncome: incomeOptions,
  },
  profileData: {
    financialProductsIds,
    seniorityLevelIds,
    benefitsIds,
    industryId,
    employmentStatusIds,
    individualIncomeId,
    occupation,
  },
  userCountryId,
  userId,
}: FinancialInfoTabProps) {
  const { control, watch } = useForm<FinancialEmploymentProfileSchema>({
    defaultValues: {
      financialProductsIds,
      seniorityLevelIds,
      benefitsIds,
      industryId,
      employmentStatusIds,
      individualIncomeId,
      occupation,
    },
    mode: "all",
  });

  const currencyToShow = getCurrencyIdFromCountry(userCountryId);

  const employedTypes = [1, 2, 3, 9]; // 1 = full time, 2 = part time, 3 = self employed, 9 = zero hours/temp
  const currentEmployment = watch("employmentStatusIds");
  const isEmployed =
    currentEmployment.some((employmentStatus: number) =>
      employedTypes.includes(employmentStatus)
    ) ?? false;

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

  return (
    <ProfileLayout>
      <div className="p-8 light text-black w-full">
        <div className="flex flex-col">
          <h1 className="font-inter text-2xl font-black tracking-tight">
            Financial & employment
          </h1>
          <p className="font-noto text-sm">
            When you finish updating this section, please click on &apos;Save my
            profile&apos;.
          </p>
        </div>
        <form
          noValidate
          action={formAction}
          className="flex flex-col pt-8 gap-4"
        >
          <Controller
            control={control}
            name="financialProductsIds"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={financialOptions}
                  description="Optional. Tell us which financial products you currently own or use."
                  fieldProps={field}
                  fieldState={fieldState}
                  isRequired={false}
                  label="Financial products"
                  name={field.name}
                  placeholder="Select all the financial products that apply"
                  selectionMode="multiple"
                />
              );
            }}
          />
          {state.errors?.financialProductsIds && (
            <FormError text={state.errors.financialProductsIds} />
          )}
          <Controller
            control={control}
            name="benefitsIds"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={benefitOptions}
                  description="Optional. If you claim any benefits, please tell us more about it."
                  fieldProps={field}
                  fieldState={fieldState}
                  isRequired={false}
                  label="Benefits"
                  name={field.name}
                  placeholder="Select all the benefit options that apply"
                  selectionMode="multiple"
                />
              );
            }}
          />
          {state.errors?.benefitsIds && (
            <FormError text={state.errors.benefitsIds} />
          )}
          <Controller
            control={control}
            name="employmentStatusIds"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={employmentOptions}
                  description="Confirm your current employment status."
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Employment status"
                  name={field.name}
                  placeholder="Select all the employment options that apply"
                  selectionMode="multiple"
                />
              );
            }}
          />
          {state.errors?.employmentStatusIds && (
            <FormError text={state.errors.employmentStatusIds} />
          )}
          <Controller
            control={control}
            name="seniorityLevelIds"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={seniorityOptions}
                  description="Seniority level is required when your employment status includes: full-time employed, part-time employed, self-employed or zero hours/temporary."
                  fieldProps={field}
                  fieldState={fieldState}
                  isRequired={isEmployed}
                  label="Seniority level"
                  name={field.name}
                  placeholder="Select all the seniority level options that apply"
                  selectionMode="multiple"
                />
              );
            }}
          />
          {state.errors?.seniorityLevelIds && (
            <FormError text={state.errors.seniorityLevelIds} />
          )}
          <Controller
            control={control}
            name="industryId"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={industryOptions}
                  description="Industry is required when your employment status includes: full-time employed, part-time employed, self-employed or zero hours/temporary. Even if you work across more than one professional area, please select only one main industry."
                  fieldProps={field}
                  fieldState={fieldState}
                  isRequired={isEmployed}
                  label="Industry"
                  name={field.name}
                  placeholder="Select one industry that best describes the area you work in"
                  selectionMode="single"
                />
              );
            }}
          />
          {state.errors?.industryId && (
            <FormError text={state.errors.industryId} />
          )}
          <Controller
            control={control}
            name="individualIncomeId"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={incomeOptions}
                  description={`Your individual annual income in ${currencyToShow}. If you are based in a country with a different currency, please roughly convert your income into pounds and choose the option that best applies.`}
                  fieldProps={field}
                  fieldState={fieldState}
                  label={`Individual income (${currencyToShow})`}
                  name={field.name}
                  placeholder="Select one income bracket"
                />
              );
            }}
          />
          {state.errors?.individualIncomeId && (
            <FormError text={state.errors.individualIncomeId} />
          )}
          <Controller
            control={control}
            name="occupation"
            render={({ fieldState, field }) => {
              return (
                <TextInput
                  isClearable
                  control={control}
                  description="Job title is required when your employment status includes: full-time employed, part-time employed, self-employed or zero hours/temporary. If you have more than one job title, please separate them with commas."
                  fieldProps={field}
                  fieldState={fieldState}
                  isRequired={isEmployed}
                  label="Job title"
                  name={field.name}
                  placeholder="Type your job title or titles."
                />
              );
            }}
          />
          {state.errors?.occupation && (
            <FormError text={state.errors.occupation} />
          )}
          {state.error && (
            <Alert
              showSupportEmail
              message={state.error}
              title={`Error (${state.errorCode})`}
              variant="error"
            />
          )}
          {state.success && (
            <Alert
              message="Your financial and employment information has been successfully updated."
              title="Success"
              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 />
        </form>
      </div>
    </ProfileLayout>
  );
}

export default FinancialEmployment;
