"use client";

import { Controller, useForm } from "react-hook-form";
import { FaSave } from "react-icons/fa";
import { FaCheck, FaCircleExclamation } from "react-icons/fa6";
import { useRouter } from "next/navigation";
import Link from "next/link";
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 { ContactInformationProfileSchema } from "@/types/profile/profile-update-schema";
import Button from "@/components/common/button";
import { AUTOCOMPLETE_VALUES } from "@/constants/signup-auto-complete-mapping";
import TextInput from "@/components/common/text-input";
import { INTERNAL_PAGES } from "@/constants/pages-mapping/internal-pages-mapping";
import { updateContactInfo } from "@/services/participant/profile/update-contact-info-actions";
import Alert from "@/components/common/alert";
import FormError from "@/components/common/form-error";
import Select from "@/components/common/select";

type ContactInformationTabProps = {
  countryOptions: Options;
  profileData: ContactInformationProfileSchema;
  isPhoneVerified: 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 ContactInformation({
  countryOptions,
  profileData: {
    email,
    countryId,
    phoneNumber,
    postCode,
    alternativeContactNumber,
  },
  isPhoneVerified,
  userId,
}: ContactInformationTabProps) {
  const router = useRouter();
  const { control } = useForm<ContactInformationProfileSchema>({
    defaultValues: {
      email,
      countryId,
      phoneNumber,
      postCode,
      alternativeContactNumber,
    },
    mode: "all",
  });

  const [state, formAction] = useFormState(
    updateContactInfo.bind(null, userId, phoneNumber, email),
    {
      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">
              Contact 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"
          >
            <div>
              <Controller
                control={control}
                name="email"
                render={({ fieldState, field }) => {
                  return (
                    <TextInput
                      isDisabled
                      autoComplete={AUTOCOMPLETE_VALUES.EMAIL}
                      control={control}
                      fieldProps={field}
                      fieldState={fieldState}
                      isClearable={false}
                      isRequired={false}
                      label="Email address"
                      name={field.name}
                      placeholder="Your email address"
                    />
                  );
                }}
              />
              <div className="font-inter font-regular text-[12px] text-gray-500 leading-tight inline-flex space-x-1">
                <p>
                  In order to update your email address, please click on this
                  link:
                </p>
                <Link
                  className="text-black font-medium underline decoration-dotted"
                  href={INTERNAL_PAGES.participant.profile.emailUpdate}
                >
                  Email update
                </Link>
                .
              </div>
            </div>
            <Controller
              control={control}
              name="countryId"
              render={({ fieldState, field }) => {
                return (
                  <Select
                    control={control}
                    data={countryOptions}
                    fieldProps={field}
                    fieldState={fieldState}
                    label="Country of residence"
                    name={field.name}
                    placeholder="Your country of residence"
                  />
                );
              }}
            />
            {state.errors?.countryId && (
              <FormError text={state.errors.countryId} />
            )}
            <Controller
              control={control}
              name="postCode"
              render={({ fieldState, field }) => {
                return (
                  <TextInput
                    isClearable
                    autoComplete={AUTOCOMPLETE_VALUES.POSTAL_CODE}
                    control={control}
                    fieldProps={field}
                    fieldState={fieldState}
                    label="Postcode/ZIP code"
                    name={field.name}
                    placeholder="Your postcode/ZIP code"
                  />
                );
              }}
            />
            {state.errors?.postCode && (
              <FormError text={state.errors.postCode} />
            )}
            <Controller
              control={control}
              name="phoneNumber"
              render={({ fieldState, field }) => {
                return (
                  <div>
                    <TextInput
                      isDisabled
                      control={control}
                      fieldProps={field}
                      fieldState={fieldState}
                      isRequired={false}
                      label="Mobile number"
                      name={field.name}
                      placeholder="Your mobile number"
                    />
                    {isPhoneVerified && (
                      <span className="font-inter font-regular text-[12px] text-gray-500 leading-tight">
                        <FaCheck className="text-green-500 inline-flex" /> Your
                        mobile number is verified. If you would like to update
                        your number, a new verification process is required. In
                        order to continue, please click on this link:{" "}
                        <button
                          className="text-black font-medium underline decoration-dotted inline-flex"
                          type="button"
                          onClick={() =>
                            router.push(
                              INTERNAL_PAGES.participant.profile
                                .manualPhoneVerification
                            )
                          }
                        >
                          Phone verification
                        </button>
                        .
                      </span>
                    )}
                    {!isPhoneVerified && (
                      <div className="flex flex-col text-center space-y-2 md:space-y-0 md:flex-row items-center space-x-1 font-inter font-regular text-[12px] text-gray-500 leading-tight">
                        <FaCircleExclamation className="text-yellow-600" />
                        <p>
                          Your mobile number is not verified. In order to update
                          and/or verify your number, please click on this link:
                        </p>
                        <button
                          className="text-black font-medium underline decoration-dotted"
                          type="button"
                          onClick={() =>
                            router.push(
                              INTERNAL_PAGES.participant.profile
                                .manualPhoneVerification
                            )
                          }
                        >
                          Phone verification
                        </button>
                        .
                      </div>
                    )}
                  </div>
                );
              }}
            />
            <Controller
              control={control}
              name="alternativeContactNumber"
              render={({ fieldState, field }) => {
                return (
                  <TextInput
                    control={control}
                    description="Optional. If you would like, please provide an alternative phone number."
                    fieldProps={field}
                    fieldState={fieldState}
                    isRequired={false}
                    label="Alternative mobile number"
                    name={field.name}
                    placeholder="Your alternative mobile number"
                  />
                );
              }}
            />
            {state.errors?.alternativeContactNumber && (
              <FormError text={state.errors.alternativeContactNumber} />
            )}
            {state.error && (
              <Alert
                showSupportEmail
                message={state.error}
                title="Error"
                variant="error"
              />
            )}
            {state.success && (
              <Alert
                message="Your contact 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 ContactInformation;
