"use client";

import { Controller, useForm } 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 { CompanyInformationProfileSchema } from "@/types/profile/profile-update-schema";
import TextInput from "@/components/common/text-input";
import Button from "@/components/common/button";
import Select from "@/components/common/select";
import RadioGroup from "@/components/common/radio-group";
import { getCurrencyIdFromCountry } from "@/utils/map-currency-profile";
import Alert from "@/components/common/alert";
import { updateCompanyInformation } from "@/services/participant/profile/update-company-information-actions";
import FormError from "@/components/common/form-error";

type ContactInfoTabProps = {
  profileData: CompanyInformationProfileSchema;
  options: {
    companyType: Options;
    companyTurnover: Options;
    tradeActivity: Options;
    companySize: Options;
    isDecisionMaker: Options;
    isVATRegistered: Options;
  };
  userCountryId: number;
  isSenior: boolean;
  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 CompanyInformation({
  profileData: {
    companyName,
    companyTypeId,
    isDecisionMaker,
    tradeActivitiesIds,
    companySizeId,
    isVATRegistered,
    companyTurnoverId,
  },
  options: {
    companyType: companyTypeOptions,
    companyTurnover: companyTurnoverOptions,
    tradeActivity: tradeActivityOptions,
    companySize: companySizeOptions,
    isDecisionMaker: decisionMakerOptions,
    isVATRegistered: isVATRegisteredOptions,
  },
  userCountryId,
  isSenior,
  userId,
}: ContactInfoTabProps) {
  const { control } = useForm<CompanyInformationProfileSchema>({
    defaultValues: {
      companyName,
      companyTypeId,
      isDecisionMaker,
      tradeActivitiesIds,
      companySizeId,
      isVATRegistered,
      companyTurnoverId,
    },
    mode: "all",
  });

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

  const currencyToUse = getCurrencyIdFromCountry(userCountryId);

  // provides a nullable option for these fields.
  const vatOptions = isSenior
    ? isVATRegisteredOptions
    : [...isVATRegisteredOptions, { id: 0, title: "Not applicable" }];

  const decisionOptions = isSenior
    ? decisionMakerOptions
    : [...decisionMakerOptions, { id: 0, title: "Not applicable" }];

  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">
            Company information
          </h1>
          <p className="font-noto text-sm">
            When you finish updating this section, please click on &apos;Save my
            profile&apos;.
          </p>
          <span className="font-noto text-sm mt-4 font-bold">
            {isSenior
              ? "⚠️ This section is required because you are a senior professional or business owner and are now a member of our business panel. The information below will help us get you involved in business/professional research."
              : "⚠️ This section is only required if you're a senior professional, which is not the case for you, as you stated on 'Financial & employment' section. Hence, this section is not required."}
          </span>
        </div>
        <form
          noValidate
          action={formAction}
          className="flex flex-col pt-8 gap-4"
        >
          <Controller
            control={control}
            name="companyName"
            render={({ fieldState, field }) => {
              return (
                <TextInput
                  isClearable
                  control={control}
                  description="We will never contact your company directly and this information is confidential, unless you give us consent to share this with a client before taking part in research."
                  fieldProps={field}
                  fieldState={fieldState}
                  isRequired={isSenior}
                  label="Company name"
                  name={field.name}
                  placeholder="Your current company name"
                />
              );
            }}
          />
          {state.errors?.companyName && (
            <FormError text={state.errors.companyName} />
          )}
          <Controller
            control={control}
            name="companyTypeId"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={companyTypeOptions}
                  fieldProps={field}
                  fieldState={fieldState}
                  isRequired={isSenior}
                  label="Company type"
                  name={field.name}
                  placeholder="Your company type"
                />
              );
            }}
          />
          {state.errors?.companyTypeId && (
            <FormError text={state.errors.companyTypeId} />
          )}
          <Controller
            control={control}
            name="isDecisionMaker"
            render={({ field, fieldState }) => {
              return (
                <RadioGroup
                  control={control}
                  data={decisionOptions}
                  fieldProps={field}
                  fieldState={fieldState}
                  isRequired={isSenior}
                  label="Key decision-maker"
                  name={field.name}
                  secondaryLabel="Are you a key decision maker within your company?"
                />
              );
            }}
          />
          {state.errors?.isDecisionMaker && (
            <FormError text={state.errors.isDecisionMaker} />
          )}
          <Controller
            control={control}
            name="tradeActivitiesIds"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={tradeActivityOptions}
                  description="Does your company import or export any goods or services?"
                  fieldProps={field}
                  fieldState={fieldState}
                  isRequired={isSenior}
                  label="International trade"
                  name={field.name}
                  placeholder="Your company trade activity"
                  selectionMode="multiple"
                />
              );
            }}
          />
          {state.errors?.tradeActivitiesIds && (
            <FormError text={state.errors.tradeActivitiesIds} />
          )}
          <Controller
            control={control}
            name="companySizeId"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={companySizeOptions}
                  fieldProps={field}
                  fieldState={fieldState}
                  isRequired={isSenior}
                  label="Company size"
                  name={field.name}
                  placeholder="Your company size"
                />
              );
            }}
          />
          {state.errors?.companySizeId && (
            <FormError text={state.errors.companySizeId} />
          )}
          <Controller
            control={control}
            name="isVATRegistered"
            render={({ field, fieldState }) => {
              return (
                <RadioGroup
                  control={control}
                  data={vatOptions}
                  fieldProps={field}
                  fieldState={fieldState}
                  isRequired={isSenior}
                  label="VAT registration"
                  name={field.name}
                  secondaryLabel="Is the company VAT registered?"
                />
              );
            }}
          />
          {state.errors?.isVATRegistered && (
            <FormError text={state.errors.isVATRegistered} />
          )}
          <Controller
            control={control}
            name="companyTurnoverId"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={companyTurnoverOptions}
                  description={`The company's turnover in ${currencyToUse}. If you are based in a country with a different currency, please roughly convert the value into pounds and choose the option that best applies.`}
                  fieldProps={field}
                  fieldState={fieldState}
                  isRequired={isSenior}
                  label={`Company turnover (${currencyToUse})`}
                  name={field.name}
                  placeholder="Your company turnover"
                />
              );
            }}
          />
          {state.errors?.companyTurnoverId && (
            <FormError text={state.errors.companyTurnoverId} />
          )}
          {state.error && (
            <Alert
              showSupportEmail
              message={state.error}
              title={`Error (${state.errorCode})`}
              variant="error"
            />
          )}
          {state.success && (
            <Alert
              message="Your company 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 CompanyInformation;
