"use client";

import { useTransition } from "react";
import { useRouter } from "next/navigation";
import { Logout03Icon } from "@hugeicons/core-free-icons";

import { Icon } from "@/components/shared/icon";
import { Button } from "@/components/ui/button";

export function LogoutButton({ compact = false }: { compact?: boolean }) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();

  function handleLogout() {
    startTransition(async () => {
      await fetch("/api/auth/logout", {
        method: "POST",
      });

      router.replace("/login");
      router.refresh();
    });
  }

  return (
    <Button
      className={compact ? "w-full" : "w-full justify-between"}
      disabled={isPending}
      onClick={handleLogout}
      size={compact ? "icon" : "default"}
      type="button"
      variant="ghost"
    >
      {compact ? null : (
        <span>{isPending ? "جارٍ تسجيل الخروج..." : "تسجيل الخروج"}</span>
      )}
      <Icon icon={Logout03Icon} size={18} />
    </Button>
  );
}
