"use client";

import { useState, useTransition } from "react";
import { useRouter } from "@/i18n/navigation";
import { useSession } from "next-auth/react";
import { useTranslations } from "next-intl";
import { AlertTriangle, X } from "lucide-react";
import Button from "@/components/ui/Button";
import { readApiJson, toastPromise } from "@/lib/toast";

export default function ImpersonationBanner() {
  const t = useTranslations("users");
  const tc = useTranslations("common");
  const { data: session, update } = useSession();
  const router = useRouter();
  const [stopping, setStopping] = useState(false);
  const [isPending, startTransition] = useTransition();

  const user = session?.user as {
    name?: string | null;
    email?: string | null;
    impersonating?: boolean;
    actorName?: string | null;
  } | undefined;

  if (!user?.impersonating) return null;

  async function stopImpersonation() {
    setStopping(true);
    try {
      await toastPromise(
        readApiJson(
          await fetch("/api/impersonate", { method: "DELETE" }),
          tc("somethingWrong")
        ),
        { loading: t("stoppingImpersonation"), success: t("impersonationStopped") }
      );
      await update({ stopImpersonate: true });
      startTransition(() => {
        router.push("/dashboard/users");
        router.refresh();
      });
    } catch {
      // toast
    } finally {
      setStopping(false);
    }
  }

  return (
    <div className="flex shrink-0 items-center justify-between gap-3 border-b border-amber-500/25 bg-amber-500/10 px-4 py-2.5 sm:px-6">
      <div className="flex min-w-0 items-center gap-2.5">
        <AlertTriangle className="h-4 w-4 shrink-0 text-amber-400" />
        <p className="truncate text-sm text-amber-200">
          {t("impersonatingAs", {
            name: user.name ?? user.email ?? "—",
            actor: user.actorName ?? "—",
          })}
        </p>
      </div>
      <Button
        variant="secondary"
        size="sm"
        onClick={stopImpersonation}
        disabled={stopping || isPending}
        className="shrink-0 border-amber-500/30 bg-amber-500/10 text-amber-200 hover:bg-amber-500/20"
      >
        <X className="h-3.5 w-3.5" />
        {t("stopImpersonation")}
      </Button>
    </div>
  );
}
