"use client";

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

import Button from "@/components/common/button";
import { PersonalInformationProfileSchema } from "@/types/profile/profile-update-schema";
import Select from "@/components/common/select";
import ProfileLayout from "@/components/pages/participant/profile/partials/profile-layout";
import { Options } from "@/types/options/options-data-types";
import { updatePersonalInformation } from "@/services/participant/profile/update-personal-info-actions";
import FormError from "@/components/common/form-error";
import Alert from "@/components/common/alert";

type PersonalInfoTabProps = {
  options: {
    genderOptions: Options;
    ethnicityOptions: Options;
    nationalityOptions: Options;
    accessibilityOptions: Options;
    techAbilityOptions: Options;
    deviceOptions: Options;
  };
  profileData: PersonalInformationProfileSchema;
  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 PersonalInformation({
  options: {
    genderOptions,
    ethnicityOptions,
    nationalityOptions,
    accessibilityOptions,
    techAbilityOptions,
    deviceOptions,
  },
  profileData: {
    firstName,
    lastName,
    dateOfBirth,
    genderId,
    ethnicityId,
    nationalityIds,
    accessibilitiesIds,
    techAbilityId,
    deviceIds,
  },
  userId,
}: PersonalInfoTabProps) {
  const { control } = useForm<PersonalInformationProfileSchema>({
    defaultValues: {
      firstName,
      lastName,
      dateOfBirth,
      genderId,
      ethnicityId,
      nationalityIds,
      accessibilitiesIds,
      techAbilityId,
      deviceIds,
    },
    mode: "all",
  });

  const [state, formAction] = useFormState(
    updatePersonalInformation.bind(
      null,
      userId,
      firstName,
      lastName,
      dateOfBirth,
      ethnicityId
    ),
    {
      success: false,
      error: "",
    }
  );

  const mappedEthinicity =
    ethnicityOptions.find((option) => option.id === ethnicityId)?.title ||
    "Unknown";

  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">
            Personal information
          </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"
        >
          <Input
            isDisabled
            classNames={{
              label: "block text-sm font-bold tracking-tight font-inter",
            }}
            description="Your first name cannot be changed. If you want to change it, please contact us."
            label="First name"
            labelPlacement="outside"
            value={firstName}
            variant="faded"
          />
          <Input
            isDisabled
            classNames={{
              label: "block text-sm font-bold tracking-tight font-inter",
            }}
            description="Your last name cannot be changed. If you want to change it, please contact us."
            label="Last name"
            labelPlacement="outside"
            value={lastName}
            variant="faded"
          />
          <Input
            isDisabled
            classNames={{
              label: "block text-sm font-bold tracking-tight font-inter",
            }}
            description="Your date of birth cannot be changed. If you want to change it, please contact us."
            label="Date of birth"
            labelPlacement="outside"
            value={dateOfBirth}
            variant="faded"
          />
          <Controller
            control={control}
            name="genderId"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={genderOptions}
                  description="The gender option that best represents you."
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Gender"
                  name={field.name}
                  placeholder="Select one gender option"
                />
              );
            }}
          />
          {state.errors?.genderId && <FormError text={state.errors.genderId} />}
          <Input
            isDisabled
            classNames={{
              label: "block text-sm font-bold tracking-tight font-inter",
            }}
            description="Your ethnicity cannot be changed. If you want to change it, please contact us."
            label="Ethnicity"
            labelPlacement="outside"
            value={mappedEthinicity}
            variant="faded"
          />
          <Controller
            control={control}
            name="nationalityIds"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={nationalityOptions}
                  description="The country/countries you belong to - by birth, descent, or naturalisation."
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Nationality"
                  name={field.name}
                  placeholder="Select all the nationality options that apply"
                  selectionMode="multiple"
                />
              );
            }}
          />
          {state.errors?.nationalityIds && (
            <FormError text={state.errors.nationalityIds} />
          )}
          <Controller
            control={control}
            name="accessibilitiesIds"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={accessibilityOptions}
                  description="Our clients recognise the importance of involving people with accessibility needs in their research and testing sessions. As long as you feel comfortable to provide this information, please confirm if you have a disability or impairment."
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Accessibility needs"
                  name={field.name}
                  placeholder="Select all the accessibility options that apply"
                  selectionMode="multiple"
                />
              );
            }}
          />
          {state.errors?.accessibilitiesIds && (
            <FormError text={state.errors.accessibilitiesIds} />
          )}
          <div className="mt-4 max-w-[300px]">
            <h4 className="text-base font-bold">Tech setup and skills</h4>
            <Divider className="my-1" />
          </div>
          <Controller
            control={control}
            name="techAbilityId"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={techAbilityOptions}
                  description="Please rate your ability when it comes to online tasks like emailing/texting, online banking, grocery shopping, etc."
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Technology ability"
                  name={field.name}
                  placeholder="Select one ability level"
                />
              );
            }}
          />
          {state.errors?.techAbilityId && (
            <FormError text={state.errors.techAbilityId} />
          )}
          <Controller
            control={control}
            name="deviceIds"
            render={({ fieldState, field }) => {
              return (
                <Select
                  control={control}
                  data={deviceOptions}
                  description="Select all the devices you own."
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Devices owned"
                  name={field.name}
                  placeholder="Select one or more devices you own"
                  selectionMode="multiple"
                />
              );
            }}
          />
          {state.errors?.deviceIds && (
            <FormError text={state.errors.deviceIds} />
          )}
          {state.error && (
            <Alert
              showSupportEmail
              message={state.error}
              title={`Error (${state.errorCode})`}
              variant="error"
            />
          )}
          {state.success && (
            <Alert
              message="Your personal 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 PersonalInformation;
