"use client";

import { useState } from "react";

import Modal from "@/components/admin/Modal";
import { Button, formatDateTime } from "@/components/admin/ui";

/**
 * Shows a freshly issued temporary password, once (spec admin-user-management, task 9.8).
 *
 * The value exists in this component's props and nowhere else — it is not stored in clear on
 * the server, not returned by any read, and not written to the audit log. Closing this dialog
 * is the last time anybody can see it, which is why the copy button is here and why the
 * dialog says so plainly rather than letting the super admin discover it by going back.
 *
 * Deliberately not persisted client-side either: no `localStorage`, no URL parameter, and it
 * disappears from React state when the dialog closes.
 */
export default function TemporaryPasswordDialog({
  email,
  password,
  expiresAt,
  onClose,
}: {
  email: string;
  password: string;
  expiresAt: string;
  onClose: () => void;
}) {
  const [copied, setCopied] = useState(false);

  async function copy() {
    try {
      await navigator.clipboard.writeText(password);
      setCopied(true);
    } catch {
      // Clipboard access can be refused (insecure context, permissions). The value is on
      // screen and selectable, so this is a convenience failing, not the flow failing.
      setCopied(false);
    }
  }

  return (
    <Modal
      title="Temporary password"
      onClose={onClose}
      footer={
        <div className="flex justify-end">
          <Button onClick={onClose}>Done</Button>
        </div>
      }
    >
      <div className="space-y-3">
        <p className="text-sm text-stone-700">
          Give this to <span className="font-medium">{email}</span>. They will be asked to set
          their own password the first time they sign in.
        </p>

        <div className="flex items-center gap-2">
          <code className="flex-1 select-all rounded-md border border-stone-300 bg-stone-50 px-3 py-2 font-mono text-base tracking-wide text-stone-900">
            {password}
          </code>
          <Button variant="secondary" onClick={copy}>
            {copied ? "Copied" : "Copy"}
          </Button>
        </div>

        <p className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900">
          <span className="font-medium">This will not be shown again.</span> Nothing can
          retrieve it — if it is lost, issue another one. It stops working on{" "}
          {formatDateTime(expiresAt)}.
        </p>

        <p className="text-xs text-stone-500">
          Send it over a channel you trust. Any existing sessions on that account have already
          been signed out.
        </p>
      </div>
    </Modal>
  );
}
