import { Modal, ModalContent, ModalHeader, ModalBody } from "@nextui-org/react";
import { FaChevronLeft, FaChevronRight } from "react-icons/fa6";
import { useForm, Controller } from "react-hook-form";
import { useEffect } from "react";
import { useFormState, useFormStatus } from "react-dom";

import Button from "@/components/common/button";
import { Options } from "@/types/options/options-data-types";
import Select from "@/components/common/select";
import TextInput from "@/components/common/text-input";
import { FinancialEmploymentProfileSchema } from "@/types/profile/profile-update-schema";
import { updateUserProfilePrompt } from "@/services/participant/opportunities/profile-prompt-actions";
import Alert from "@/components/common/alert";
import FormError from "@/components/common/form-error";
import useMediaBreakpoints from "@/hooks/useMediaBreakpoints";

type ProfilePromptProps = {
  isOpen: boolean;
  userDetails: FinancialEmploymentProfileSchema;
  employmentOptions: Options;
  industryOptions: Options;
  seniorityOptions: Options;
  userId: number;
  onClose: () => void;
  onClickContinue: () => void;
};

function SubmitButton({ onClose }: { onClose: () => void }) {
  const { pending } = useFormStatus();

  return (
    <div className="flex flex-col space-y-4 space-x-0 xl:space-y-0 xl:space-x-2 xl:flex-row xl:justify-between">
      <Button
        fullWidth
        btnLabel="Go back"
        customVariant="transparent-black"
        startContent={<FaChevronLeft />}
        onClick={onClose}
      />
      <Button
        fullWidth
        aria-disabled={pending}
        btnLabel={pending ? "Saving..." : "Continue to survey"}
        customVariant="black"
        endContent={pending ? null : <FaChevronRight />}
        isDisabled={pending}
        isLoading={pending}
        type="submit"
      />
    </div>
  );
}

function ProfilePrompt({
  isOpen,
  userDetails,
  employmentOptions,
  industryOptions,
  seniorityOptions,
  userId,
  onClose,
  onClickContinue,
}: ProfilePromptProps) {
  const viewport = useMediaBreakpoints();
  const isMobile = viewport === "mobile";
  const { control, watch } = useForm<FinancialEmploymentProfileSchema>({
    defaultValues: {
      employmentStatusIds: userDetails?.employmentStatusIds ?? [],
      industryId: userDetails?.industryId ?? 0,
      occupation: userDetails?.occupation ?? "",
      seniorityLevelIds: userDetails?.seniorityLevelIds ?? [],
    },
    mode: "all",
  });

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

  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;

  useEffect(() => {
    if (state.success) {
      onClose();
      onClickContinue();
    }
  }, [onClickContinue, onClose, state.success]);

  return (
    <Modal
      backdrop="blur"
      className="p-2"
      classNames={{
        base: "light",
      }}
      isDismissable={false}
      isOpen={isOpen}
      size={isMobile ? "full" : "3xl"}
      onClose={onClose}
    >
      <ModalContent className="text-black">
        <ModalHeader className="flex flex-col">
          <h3 className="inline-flex font-inter items-center font-black text-xl tracking-tight">
            Confirm your profile details
          </h3>
          <p className="text-sm text-gray-600 font-normal">
            Please confirm if the following information is up-to-date.
          </p>
        </ModalHeader>
        <ModalBody className="font-noto text-sm">
          <form noValidate action={formAction} className="flex flex-col gap-4">
            <Controller
              control={control}
              name="occupation"
              render={({ fieldState, field }) => {
                return (
                  <TextInput
                    isClearable
                    control={control}
                    description="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="Your current job title"
                  />
                );
              }}
            />
            {state.errors?.occupation && (
              <FormError text={state.errors.occupation} />
            )}
            <Controller
              control={control}
              name="industryId"
              render={({ fieldState, field }) => {
                return (
                  <Select
                    control={control}
                    data={industryOptions}
                    description="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="employmentStatusIds"
              render={({ fieldState, field }) => {
                return (
                  <Select
                    control={control}
                    data={employmentOptions}
                    description="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} />
            )}
            {state.error && (
              <Alert
                message={state.error}
                title={`Error (${state.errorCode})`}
                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 onClose={onClose} />
          </form>
        </ModalBody>
      </ModalContent>
    </Modal>
  );
}

export default ProfilePrompt;
