"use client";

import { FiLogOut } from "react-icons/fi";
import Button from "../ui/Button";
import { useModal } from "../../lib/modal-system/ModalContext";
import useLogout from "../../hooks/features/auth/logout/useLogout";
import { useRouter } from "next/navigation";
import { useState } from "react";

export default function LogoutModal() {
  const { closeModal } = useModal();
  const { handleLogout } = useLogout();
  const router = useRouter();

  const [loading, setLoading] = useState<boolean>(false);

  const logout = async () => {
    try {
      setLoading(true);

      await handleLogout();
      closeModal();
      await fetch(`/api/auth/logout`, {
        method: "POST",
        body: JSON.stringify({}),
      });

      window.location.replace("/");
    } catch (error) {
      closeModal();
      await fetch(`/api/auth/logout`, {
        method: "POST",
        body: JSON.stringify({}),
      });

      window.location.replace("/");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="text-center">
      <div className="mx-auto flex h-24 w-24 items-center justify-center rounded-full bg-danger-light">
        <div className="flex h-15 w-15 items-center justify-center rounded-full bg-danger-400 text-white">
          <FiLogOut size={24} />
        </div>
      </div>

      <h2 className="mx-auto mt-8 max-w-80 font-heading text-lg font-bold text-heading">
        Are you sure you want to sign out?
      </h2>

      <p className="mx-auto mt-5 max-w-97 font-body text-base leading-6 text-[#54545F]">
        You'll need to sign in again to access your account
      </p>

      <div className="mt-8 flex items-center justify-center gap-4 flex-wrap">
        <Button
          type="button"
          variant="white"
          onClick={closeModal}
          buttonClassName="shadow-none!"
          BtnInnerclassName="text-link!"
        >
          No, Go Back
        </Button>

        <Button
          type="button"
          variant="white"
          loading={loading}
          onClick={logout}
          buttonClassName="shadow-none! p-0!"
          BtnInnerclassName="rounded-full border-danger-400 border !text-danger"
        >
          Yes, Sign Out
        </Button>
      </div>
    </div>
  );
}
