"use client";
// 2026-11-10: "Login as user" — visible to Super Admin only (the backend checks the role again).
import { useEffect, useState } from "react";
import { FiLogIn } from "react-icons/fi";
import toast from "react-hot-toast";
import { isSuperAdminSession, loginAsUser } from "./impersonation";

export default function LoginAsButton({
  userId,
  name,
  variant = "icon",
}: {
  userId: number;
  name: string;
  variant?: "icon" | "button";
}) {
  const [allowed, setAllowed] = useState(false);
  const [busy, setBusy] = useState(false);

  useEffect(() => setAllowed(isSuperAdminSession()), []);
  if (!allowed) return null;

  const go = async () => {
    if (busy) return;
    if (!window.confirm(`Log in as ${name}?\n\nYou will see the CRM exactly as this user does. Use "Return to my account" in the orange bar to come back.`)) return;
    setBusy(true);
    try {
      await loginAsUser(userId, name);
    } catch (e: any) {
      toast.error(e?.message || "Could not log in as this user.");
      setBusy(false);
    }
  };

  if (variant === "button") {
    return (
      <button
        onClick={go}
        disabled={busy}
        style={{ display: "flex", alignItems: "center", gap: 6, padding: "8px 16px", borderRadius: 8, border: "none", background: "#fff7ed", color: "#c2410c", fontWeight: 600, fontSize: 13, cursor: "pointer" }}
      >
        <FiLogIn size={16} /> {busy ? "Opening…" : "Login as user"}
      </button>
    );
  }
  return (
    <button
      onClick={go}
      disabled={busy}
      title={`Login as ${name}`}
      style={{ padding: "5px 8px", borderRadius: 6, border: "none", background: "#fff7ed", color: "#c2410c", cursor: busy ? "wait" : "pointer" }}
    >
      <FiLogIn size={14} />
    </button>
  );
}
