"use client";

import type { ReactNode } from "react";
import { useRouter } from "next/navigation";
import { LogOut } from "lucide-react";
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";

import { useLocale } from "@/components/providers/locale-provider";

type LogoutButtonProps = {
  className?: string;
  label?: string;
  icon?: ReactNode;
};

export function LogoutButton({
  className,
  label,
  icon
}: LogoutButtonProps) {
  const router = useRouter();
  const { dict } = useLocale();
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!open) return;

    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    function handleKeyDown(event: KeyboardEvent) {
      if (event.key === "Escape") {
        setOpen(false);
      }
    }

    window.addEventListener("keydown", handleKeyDown);

    return () => {
      document.body.style.overflow = previousOverflow;
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [open]);

  async function handleLogout() {
    setLoading(true);
    try {
      await fetch("/api/v1/auth/logout", {
        method: "POST"
      });
      router.push("/login");
      router.refresh();
    } finally {
      setLoading(false);
    }
  }

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        disabled={loading}
        className={className}
      >
        {icon}
        <span>{loading ? dict.common.processing : label ?? dict.common.logout}</span>
      </button>

      {mounted && open
        ? createPortal(
            <div
              className="fixed inset-0 z-[200] overflow-y-auto"
              role="dialog"
              aria-modal="true"
              aria-labelledby="logout-modal-title"
              onClick={(event) => {
                if (event.target === event.currentTarget && !loading) {
                  setOpen(false);
                }
              }}
            >
              <div className="fixed inset-0 bg-slate-900/50 backdrop-blur-sm transition-opacity" />
              <div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
                <div className="relative w-full max-w-md transform overflow-hidden rounded-xl border border-line/70 bg-white px-4 pb-4 pt-5 text-left shadow-xl transition-all sm:my-8 sm:p-6">
                  <div className="sm:flex sm:items-start">
                    <div className="mx-auto flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-red-50 text-red-600 sm:mx-0 sm:h-10 sm:w-10">
                      <LogOut className="h-5 w-5" />
                    </div>
                    <div className="mt-3 text-center sm:ml-4 sm:mt-0 sm:text-left">
                      <h3 id="logout-modal-title" className="text-[16px] font-semibold text-ink">
                        {dict.common.logoutModalTitle}
                      </h3>
                      <div className="mt-2">
                        <p className="text-[13px] leading-6 text-slate-600">
                          {dict.common.logoutModalDescription}
                        </p>
                      </div>
                    </div>
                  </div>
                  <div className="mt-6 flex flex-col gap-3 sm:mt-8 sm:flex-row-reverse">
                    <button
                      type="button"
                      onClick={() => void handleLogout()}
                      disabled={loading}
                      className="inline-flex w-full justify-center rounded-lg bg-red-600 px-4 py-2 text-[13px] font-semibold text-white shadow-sm transition-colors hover:bg-red-700 disabled:cursor-not-allowed disabled:opacity-60 sm:w-auto"
                    >
                      {loading ? dict.common.processing : dict.common.logoutNow}
                    </button>
                    <button
                      type="button"
                      onClick={() => setOpen(false)}
                      disabled={loading}
                      className="inline-flex w-full justify-center rounded-lg border border-line/70 bg-white px-4 py-2 text-[13px] font-semibold text-slate-600 shadow-sm transition-colors hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-60 sm:w-auto"
                    >
                      {dict.common.cancel}
                    </button>
                  </div>
                </div>
              </div>
            </div>,
            document.body
          )
        : null}
    </>
  );
}
