"use client";

import { Controller, useForm } from "react-hook-form";
import { useEffect, useState } from "react";
import { FaCheckCircle, FaChevronLeft, FaChevronRight } from "react-icons/fa";
import { useRouter } from "next/navigation";
import { useFormState, useFormStatus } from "react-dom";
import toast from "react-hot-toast";

import Breadcrumbs from "@/components/common/breadcrumbs";
import Select from "@/components/common/select";
import TextArea from "@/components/common/textarea";
import { Options } from "@/types/options/options-data-types";
import ProgressBar from "@/components/common/progress-bar";
import Button from "@/components/common/button";
import { deleteUserAccount } from "@/services/participant/profile/update-account-settings-actions";
import Alert from "@/components/common/alert";
import TextInput from "@/components/common/text-input";
import { deleteSession } from "@/lib/user-session";
import { INTERNAL_PAGES } from "@/constants/pages-mapping/internal-pages-mapping";

type DeleteMyAccountProps = {
  userFirstName: string;
  userEmail: string;
  options: Options;
};

type DeleteAccountSchema = {
  feedbackStatusId: number;
  feedback?: string;
  emailConfirmation?: string;
};

function SubmitButton({ isEmailConfirmed }: { isEmailConfirmed: boolean }) {
  const { pending } = useFormStatus();

  return (
    <Button
      fullWidth
      aria-disabled={pending || !isEmailConfirmed}
      btnLabel={
        pending ? "Processing request..." : "Yes, I want to delete my account"
      }
      className="bg-red-500 hover:bg-red-600 text-white"
      endContent={pending ? null : <FaChevronRight />}
      isDisabled={!isEmailConfirmed || pending}
      isLoading={pending}
      type="submit"
    />
  );
}

function DeleteMyAccount({
  userFirstName,
  userEmail,
  options,
}: DeleteMyAccountProps) {
  const router = useRouter();
  const [currentStep, setCurrentStep] = useState(1);
  const { control, watch } = useForm<DeleteAccountSchema>({
    defaultValues: {
      feedbackStatusId: 0,
      feedback: "",
      emailConfirmation: "",
    },
    mode: "onChange",
  });

  const selectedReasonId = watch("feedbackStatusId");
  const userFeedback = watch("feedback");
  const emailConfirmation = watch("emailConfirmation");

  const isEmailConfirmed =
    emailConfirmation !== "" && emailConfirmation === userEmail;

  const isOtherReasonSelected =
    options.find((option) => option.title.toLowerCase().includes("other"))
      ?.id === selectedReasonId;

  const countCharsOther = userFeedback ? userFeedback.length : 0;

  const handleClickGoBack = () => {
    router.back();
  };

  const onClickContinue = () => {
    if (currentStep === 1) {
      setCurrentStep(2);
    } else {
      setCurrentStep(1);
    }
  };

  const onClickBackFirstStep = () => {
    setCurrentStep(1);
  };

  const [state, formAction] = useFormState(deleteUserAccount, {
    success: false,
    error: "",
  });

  useEffect(() => {
    if (state.success) {
      deleteSession();
      toast.success(
        "Your account has been deleted successfully. Redirecting to the homepage..."
      );
      router.push(INTERNAL_PAGES.participant.homepage);
    }
  }, [router, state.success]);

  return (
    <div className="mb-24">
      <div className="block lg:hidden m-4">
        <Breadcrumbs />
      </div>
      <div className="bg-white p-8 rounded-md m-4 sm:m-20 lg:m-auto mt-4 lg:w-1/2 lg:h-1/2 lg:mt-12">
        <ProgressBar
          className="mb-8"
          classNames={{
            label: "text-sm font-bold text-black tracking-tight font-inter",
            indicator:
              "bg-gradient-to-r dark:from-paleBlue dark:to-participant-cerulean from-peach to-participant-bittersweet",
          }}
          label={`Account deletion journey (${currentStep}/2)`}
          maxValue={2}
          minValue={1}
          value={currentStep === 2 ? currentStep - 0.2 : currentStep + 0.1}
        />
        <div className="mt-4 space-y-4 text-black">
          <h1 className="font-inter text-xl font-extrabold tracking-tight">
            Delete my account
          </h1>
          {currentStep === 1 && (
            <>
              <p className="text-sm leading-6">
                This action will permanently delete your People for Research
                account. You will no longer be able to log into your account, or
                apply for research opportunities.
              </p>
              <p className="text-sm leading-6">
                We&apos;ll also permanently delete all the data we hold for you,
                across all systems. Your data will be deleted within 1 month of
                you deleting your account, in line with current data protection
                and UK GDPR laws.
              </p>
              <p className="text-sm leading-6">
                If you&apos;re unsure about deleting your account permanently,
                you may prefer to close it instead. This will prevent contact
                but keep your data securely stored in case you return. In case
                you want to close your account instead, please navigate to your
                account settings and select the option to close your account.
              </p>
              <p className="text-sm font-noto font-bold pt-4">
                {userFirstName}, to permanently delete your account, please
                press continue.
              </p>
              <div className="flex flex-col lg:flex-row lg:justify-between gap-2 py-4">
                <Button
                  fullWidth
                  btnLabel="Go back"
                  customVariant="transparent-black"
                  startContent={<FaChevronLeft />}
                  onClick={handleClickGoBack}
                />
                <Button
                  fullWidth
                  btnLabel="Continue"
                  customVariant="black"
                  endContent={<FaChevronRight />}
                  variant="solid"
                  onClick={onClickContinue}
                />
              </div>
            </>
          )}
          {currentStep === 2 && (
            <>
              <p className="text-sm">
                We&apos;re sorry to see you go. Deleting your account will do
                the following:
              </p>
              <ul className="list-disc ps-2">
                <li className="text-sm inline-flex items-center gap-2">
                  <FaCheckCircle className="text-green-500" />
                  You will be logged out of your account automatically.
                </li>
                <li className="text-sm inline-flex items-center gap-2">
                  <FaCheckCircle className="text-green-500" />
                  Your data will be permanently deleted from all of our systems.
                </li>
              </ul>
              <p className="text-sm">
                If you&apos;re willing to share before you leave, your feedback
                could help us improve the platform.
              </p>
              <form noValidate action={formAction} className="space-y-3">
                <Controller
                  control={control}
                  name="feedbackStatusId"
                  render={({ field, fieldState }) => {
                    return (
                      <Select
                        control={control}
                        data={options}
                        description="Optional."
                        fieldProps={field}
                        fieldState={fieldState}
                        isRequired={false}
                        label="Let us know why you're deleting your account."
                        name={field.name}
                        placeholder="Select an option"
                      />
                    );
                  }}
                />
                {isOtherReasonSelected && (
                  <Controller
                    control={control}
                    name="feedback"
                    render={({ fieldState, field }) => {
                      return (
                        <TextArea
                          control={control}
                          description="Optional."
                          fieldProps={field}
                          fieldState={fieldState}
                          isRequired={false}
                          label={`Please describe why you're deleting your account. (${countCharsOther}/200 characters)`}
                          maxLength={200}
                          minLength={2}
                          minRows={4}
                          name={field.name}
                          placeholder="Enter your reason(s)"
                        />
                      );
                    }}
                  />
                )}
                <p className="text-sm">
                  {`${userFirstName}, are you sure you want to permanently delete your People for Research account? This action cannot be undone.`}
                </p>
                <Controller
                  control={control}
                  name="emailConfirmation"
                  render={({ field, fieldState }) => {
                    return (
                      <TextInput
                        blockCopyPaste
                        autoComplete="off"
                        control={control}
                        fieldProps={field}
                        fieldState={fieldState}
                        label={`To confirm, type "${userEmail}" in the box below:`}
                        name={field.name}
                        placeholder="Enter your email address"
                        type="email"
                      />
                    );
                  }}
                />
                <div className="flex flex-col lg:flex-row lg:justify-between gap-2 py-4">
                  <Button
                    fullWidth
                    btnLabel="Go back to first step"
                    customVariant="transparent-black"
                    startContent={<FaChevronLeft />}
                    onClick={onClickBackFirstStep}
                  />
                  <SubmitButton isEmailConfirmed={isEmailConfirmed} />
                </div>
              </form>
            </>
          )}
          {state.error && (
            <Alert
              showSupportEmail
              message="There was an error while performing this action. Please try again or contact us at "
              title="Error"
              variant="error"
            />
          )}
        </div>
      </div>
    </div>
  );
}

export default DeleteMyAccount;
