"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 { LifeProfileSchema } from "@/types/profile/profile-update-schema";
import Select from "@/components/common/select";
import Button from "@/components/common/button";
import RadioGroup from "@/components/common/radio-group";
import { updateLifeChoices } from "@/services/participant/profile/update-life-choices-actions";
import Alert from "@/components/common/alert";
import FormError from "@/components/common/form-error";

type LifeTabProps = {
  options: {
    maritalStatusOptions: Options;
    childrenOptions: Options;
    householdOptions: Options;
    educationOptions: Options;
    drivingOptions: Options;
  };
  profileData: LifeProfileSchema;
  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 Life({
  options: {
    maritalStatusOptions,
    childrenOptions,
    householdOptions,
    educationOptions,
    drivingOptions,
  },
  profileData: {
    maritalStatusId,
    hasChildren,
    householdIds,
    drivingOptionsIds,
    educationLevelId,
  },
  userId,
}: LifeTabProps) {
  const { control } = useForm<LifeProfileSchema>({
    defaultValues: {
      maritalStatusId,
      hasChildren,
      householdIds,
      drivingOptionsIds,
      educationLevelId,
    },
    mode: "all",
  });

  const [state, formAction] = useFormState(
    updateLifeChoices.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">
            Life choices
          </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="maritalStatusId"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={maritalStatusOptions}
                  description="Your current marital status."
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Marital status"
                  name={field.name}
                  placeholder="Select one marital status option"
                />
              );
            }}
          />
          {state.errors?.maritalStatusId && (
            <FormError text={state.errors.maritalStatusId} />
          )}
          <Controller
            control={control}
            name="hasChildren"
            render={({ fieldState, field }) => {
              return (
                <RadioGroup
                  control={control}
                  data={childrenOptions}
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Children"
                  name={field.name}
                  secondaryLabel="Do you have any children under the age of 18?"
                />
              );
            }}
          />
          {state.errors?.hasChildren && (
            <FormError text={state.errors.hasChildren} />
          )}
          <Controller
            control={control}
            name="householdIds"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={householdOptions}
                  description="The current living situation that best describes you."
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Household"
                  name={field.name}
                  placeholder="Select all the options that apply"
                  selectionMode="multiple"
                />
              );
            }}
          />
          {state.errors?.householdIds && (
            <FormError text={state.errors.householdIds} />
          )}
          <Controller
            control={control}
            name="educationLevelId"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={educationOptions}
                  description="The highest level of education achieved."
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Education level"
                  name={field.name}
                  placeholder="Select one education level option"
                />
              );
            }}
          />
          {state.errors?.educationLevelId && (
            <FormError text={state.errors.educationLevelId} />
          )}
          <Controller
            control={control}
            name="drivingOptionsIds"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={drivingOptions}
                  description="The vehicles you can drive or own."
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Driving & vehicles"
                  name={field.name}
                  placeholder="Select all the driving options that apply"
                  selectionMode="multiple"
                />
              );
            }}
          />
          {state.errors?.drivingOptionsIds && (
            <FormError text={state.errors.drivingOptionsIds} />
          )}
          {state.error && (
            <Alert
              showSupportEmail
              message={state.error}
              title={`Error (${state.errorCode})`}
              variant="error"
            />
          )}
          {state.success && (
            <Alert
              message="Your life choices 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 Life;
