"use client";

import { useState } from "react";
import Link from "next/link";
import { ShieldAlert } from "lucide-react";

import { Button } from "@/components/ui/button";
import { toastApiError } from "@/lib/toast-api-error";

import { launchImpersonationInNewTab } from "../_lib/start-impersonation";

type CustomerImpersonateConfirmProps = {
  customerId: number;
  customerName: string;
  tenant: string;
  parentCustomerId?: number;
};

/**
 * Explicit confirmation before starting an impersonation session.
 *
 * This page used to redirect straight into the impersonation endpoint on load, which made
 * `/dashboard/customers/{id}?action=impersonate` a link that silently signed an admin in as
 * someone else. Starting a session is now a deliberate click, and it is recorded in the
 * impersonation audit log against the admin who made it.
 */
export function CustomerImpersonateConfirm({
  customerId,
  customerName,
  tenant,
  parentCustomerId,
}: CustomerImpersonateConfirmProps) {
  const [starting, setStarting] = useState(false);

  async function handleStart() {
    setStarting(true);
    try {
      await launchImpersonationInNewTab({ customerId, parentCustomerId });
    } catch (error) {
      toastApiError(error, "Could not start impersonation.");
    } finally {
      setStarting(false);
    }
  }

  return (
    <div className="mx-auto flex max-w-xl flex-col gap-5 rounded-lg border p-6">
      <div className="flex items-start gap-3">
        <div className="flex size-9 shrink-0 items-center justify-center rounded-md border border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-400">
          <ShieldAlert className="size-4.5" />
        </div>
        <div className="flex flex-col gap-1">
          <h1 className="text-lg font-semibold">Sign in as {customerName}</h1>
          <p className="text-sm text-muted-foreground">
            You will see the <span className="font-medium text-foreground">{tenant}</span> portal
            exactly as this customer does, in a new tab. The session is recorded against your
            account and ends when you choose Exit impersonation.
          </p>
        </div>
      </div>

      <div className="flex flex-wrap items-center gap-2">
        <Button type="button" disabled={starting} onClick={() => void handleStart()}>
          {starting ? "Starting…" : "Start impersonation"}
        </Button>
        <Button variant="outline" asChild>
          <Link href="/dashboard/customers">Cancel</Link>
        </Button>
      </div>
    </div>
  );
}
