"use client";

import { Controller, useForm } from "react-hook-form";
import { FaSave } from "react-icons/fa";
import { useEffect, useState } from "react";
import { MdDeleteForever } from "react-icons/md";
import {
  Card,
  CardBody,
  CardFooter,
  CardHeader,
  useDisclosure,
} from "@nextui-org/react";
import { useFormState, useFormStatus } from "react-dom";
import { FaBoxArchive } from "react-icons/fa6";
import { useRouter } from "next/navigation";

import ProfileLayout from "@/components/pages/participant/profile/partials/profile-layout";
import { AccountManagementSchema } from "@/types/profile/profile-update-schema";
import Button from "@/components/common/button";
import PasswordInput from "@/components/common/password-input";
import { AUTOCOMPLETE_VALUES } from "@/constants/signup-auto-complete-mapping";
import {
  closeUserAccount,
  updateAccountSettings,
} from "@/services/participant/profile/update-account-settings-actions";
import Alert from "@/components/common/alert";
import { deleteSession } from "@/lib/user-session";
import CloseAccountModal from "@/components/pages/participant/profile/partials/close-account-modal";
import { INTERNAL_PAGES } from "@/constants/pages-mapping/internal-pages-mapping";

type AccountManagementProps = {
  userFirstName: string;
};

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

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

function AccountManagement({ userFirstName }: AccountManagementProps) {
  const router = useRouter();

  const {
    isOpen: isCloseAccountOpen,
    onOpen: openCloseAccountModal,
    onClose: closeCloseAccountModal,
  } = useDisclosure();

  const [hasError, setHasError] = useState(false);

  const { control, reset } = useForm<AccountManagementSchema>({
    defaultValues: {
      currentPassword: "",
      newPassword: "",
      passwordConfirmation: "",
    },
    mode: "all",
  });

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

  useEffect(() => {
    if (state.success) {
      reset();
    }
  }, [reset, state.success]);

  const handleLogout = () => {
    deleteSession();
  };

  const handleCloseAccount = async () => {
    const response = await closeUserAccount();

    if (response.success) {
      setHasError(false);
      closeCloseAccountModal();
      handleLogout();
    } else {
      setHasError(true);
      closeCloseAccountModal();
    }
  };

  const handleClickDeleteAccount = () => {
    router.push(INTERNAL_PAGES.participant.profile.deleteMyAccount);
  };

  return (
    <ProfileLayout>
      <div className="p-8 light text-black w-full">
        <div className="flex flex-col space-y-4">
          <h1 className="font-inter text-2xl font-black tracking-tight">
            Account settings
          </h1>
          <div className="flex flex-col">
            <span className="font-inter font-black">Password management</span>
            <span className="text-gray-600 text-sm">
              This section allows you to change your password.
            </span>
          </div>
        </div>
        <form
          noValidate
          action={formAction}
          className="flex flex-col pt-8 gap-4"
        >
          <Controller
            control={control}
            name="currentPassword"
            render={({ fieldState, field }) => {
              return (
                <PasswordInput
                  autoComplete={AUTOCOMPLETE_VALUES.CURRENT_PASSWORD}
                  control={control}
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Current password"
                  name={field.name}
                  placeholder="Current password"
                  showGuidelines={false}
                />
              );
            }}
          />
          <Controller
            control={control}
            name="newPassword"
            render={({ fieldState, field }) => {
              return (
                <PasswordInput
                  autoComplete={AUTOCOMPLETE_VALUES.NEW_PASSWORD}
                  control={control}
                  fieldProps={field}
                  fieldState={fieldState}
                  label="New password"
                  name={field.name}
                  placeholder="New password"
                />
              );
            }}
          />
          <Controller
            control={control}
            name="passwordConfirmation"
            render={({ fieldState, field }) => {
              return (
                <PasswordInput
                  autoComplete={AUTOCOMPLETE_VALUES.NEW_PASSWORD}
                  control={control}
                  fieldProps={field}
                  fieldState={fieldState}
                  label="Confirm new password"
                  name={field.name}
                  placeholder="Confirm new password"
                  showGuidelines={false}
                />
              );
            }}
          />
          {state.error && (
            <Alert
              message={state.error}
              title={`Error ${state.errorCode ? `(${state.errorCode})` : ""}`}
              variant="error"
            />
          )}
          {state.success && (
            <Alert
              message="Your password has been successfully updated."
              title="Success"
              variant="success"
            />
          )}
          {hasError && (
            <Alert
              showSupportEmail
              message="There was an error while performing this action. Please try again or contact us at "
              title="Error"
              variant="error"
            />
          )}
          {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 />
          <div className="flex flex-col border border-red-100 rounded-md bg-red-50 p-8 mt-8 space-y-4">
            <span className="font-inter font-black text-red-900 text-lg">
              Danger zone
            </span>
            <Card className="w-full shadow-none rounded flex flex-row justify-between p-2">
              <div className="w-2/3">
                <CardHeader className="font-inter font-bold pb-0">
                  Close my account
                </CardHeader>
                <CardBody className="text-sm text-gray-600 pt-0">
                  This action allows you to close your account with People for
                  Research.
                </CardBody>
              </div>
              <CardFooter className="flex flex-col items-end justify-center w-2/3">
                <Button
                  fullWidth
                  btnLabel="Close account"
                  className="bg-amber-100 text-black"
                  startContent={<FaBoxArchive className="size-4" />}
                  type="button"
                  onClick={openCloseAccountModal}
                />
              </CardFooter>
            </Card>
            <Card className="w-full shadow-none rounded flex flex-row justify-between p-2">
              <div className="w-2/3">
                <CardHeader className="font-inter font-bold pb-0">
                  Delete my account
                </CardHeader>
                <CardBody className="text-sm text-gray-600 pt-0">
                  This action allows you to permanently delete your account,
                  along with all data People for Research holds on you. This
                  action cannot be undone.
                </CardBody>
              </div>
              <CardFooter className="flex flex-col items-end justify-center w-2/3">
                <Button
                  fullWidth
                  btnLabel="Delete account & data erasure request"
                  className="bg-red-200 text-black"
                  startContent={<MdDeleteForever className="size-4" />}
                  type="button"
                  onClick={handleClickDeleteAccount}
                />
              </CardFooter>
            </Card>
          </div>
        </form>
        {isCloseAccountOpen && (
          <CloseAccountModal
            isOpen={isCloseAccountOpen}
            userFirstName={userFirstName}
            onClickDelete={handleCloseAccount}
            onClose={closeCloseAccountModal}
          />
        )}
      </div>
    </ProfileLayout>
  );
}

export default AccountManagement;
