"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 { PreferencesProfileSchema } from "@/types/profile/profile-update-schema";
import RadioGroup from "@/components/common/radio-group";
import Button from "@/components/common/button";
import { updatePreferences } from "@/services/participant/profile/update-preferences-actions";
import FormError from "@/components/common/form-error";
import Alert from "@/components/common/alert";

type PreferencesProps = {
  defaultOptions: Options;
  isSubscribed: boolean;
  isSubscribedPrizeDraws: boolean;
  userId: number;
};

function SubmitButton() {
  const { pending } = useFormStatus();

  return (
    <Button
      fullWidth
      aria-disabled={pending}
      btnLabel={pending ? "Saving data..." : "Save my preferences"}
      className="mt-4"
      customVariant="black"
      isDisabled={pending}
      isLoading={pending}
      startContent={pending ? null : <FaSave />}
      type="submit"
    />
  );
}

function Preferences({
  isSubscribed,
  isSubscribedPrizeDraws,
  defaultOptions,
  userId,
}: PreferencesProps) {
  const { control } = useForm<PreferencesProfileSchema>({
    defaultValues: {
      isSubscribed,
      isSubscribedPrizeDraws,
    },
    mode: "all",
  });

  const [state, formAction] = useFormState(
    updatePreferences.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">
            Preferences
          </h1>
          <p className="font-noto text-sm">
            When you finish updating this section, please click on &apos;Save my
            preferences&apos;.
          </p>
        </div>
        <form
          noValidate
          action={formAction}
          className="flex flex-col pt-8 gap-4"
        >
          <Controller
            control={control}
            name="isSubscribedPrizeDraws"
            render={({ fieldState, field }) => {
              return (
                <RadioGroup
                  control={control}
                  data={defaultOptions}
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Surveys with prize draws"
                  name={field.name}
                  secondaryLabel="I want to hear about surveys with prize draws."
                />
              );
            }}
          />
          {state.errors?.isSubscribedPrizeDraws && (
            <FormError text={state.errors.isSubscribedPrizeDraws} />
          )}
          <Controller
            control={control}
            name="isSubscribed"
            render={({ fieldState, field }) => {
              return (
                <RadioGroup
                  showPrivacyPolicyLink
                  control={control}
                  data={defaultOptions}
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Communications and emails"
                  name={field.name}
                  secondaryLabel="We will only send you opportunities as long as you are still happy to hear from us. If you wish to unsubscribe, you can do so at any time by opting out below. Please allow up to 7 days for your request to take effect due to already scheduled emails. Unsubscribing means you won't receive any more invites to apply to opportunities, but you will still be able to log into your account on our website and apply to paid research. If you do apply, you accept that we are allowed to contact you solely for the purpose of getting you involved in the research you apply for. For further information on how we handle your data, please read our "
                />
              );
            }}
          />
          {state.errors?.isSubscribed && (
            <FormError text={state.errors.isSubscribed} />
          )}
          {state.error && (
            <Alert
              showSupportEmail
              message={state.error}
              title={`Error (${state.errorCode})`}
              variant="error"
            />
          )}
          {state.success && (
            <Alert
              message="Your preferences have 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 Preferences;
