"use client";

import { CopyOutlined } from "@ant-design/icons";
import { Alert, Button, Modal, Space, Typography, message } from "antd";

const { Text, Paragraph } = Typography;

export type CopyOnceModalProps = {
  open: boolean;
  /** Plaintext API key. Lives only once in the parent's in-memory state; this component persists nothing. */
  apiKey: string;
  /** Fired after the user clicks "I've saved it, close" in the second confirmation; the parent clears the plaintext and navigates away. */
  onClose: () => void;
  /** Shared by create and rotate flows; the rotate flow may pass e.g. "API Key Rotated". */
  title?: string;
};

// Fallback copy path for browsers where navigator.clipboard is unavailable (non-secure context).
function fallbackCopyText(text: string) {
  const textarea = document.createElement("textarea");
  textarea.value = text;
  textarea.style.position = "fixed";
  textarea.style.opacity = "0";
  document.body.appendChild(textarea);
  textarea.select();
  const copied = document.execCommand("copy");
  document.body.removeChild(textarea);
  return copied;
}

// Copy-once plaintext modal (plan doc section 5.2):
// the plaintext key appears only once in the create/rotate response; after closing,
// the system stores only its hash and it can never be viewed again.
// Therefore the modal allows no accidental-close path (no top-right X, mask click disabled, ESC disabled);
// the only exit is the "I've saved it" button, guarded by a second confirmation.
export function CopyOnceModal({
  open,
  apiKey,
  onClose,
  title = "API Key Created",
}: CopyOnceModalProps) {
  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(apiKey);
      message.success("Copied");
    } catch {
      if (fallbackCopyText(apiKey)) {
        message.success("Copied");
      } else {
        message.error("Copy failed. Please select the text and copy it manually.");
      }
    }
  };

  const handleConfirmSaved = () => {
    Modal.confirm({
      title: "Have you saved this API Key securely?",
      content: "Once closed, the plaintext key cannot be viewed again.",
      okText: "I've saved it, close",
      cancelText: "Check again",
      onOk: onClose,
    });
  };

  return (
    <Modal
      open={open}
      centered
      width={720}
      closable={false}
      maskClosable={false}
      keyboard={false}
      title={title}
      footer={
        <Button type="primary" onClick={handleConfirmSaved}>
          I&apos;ve Saved It
        </Button>
      }
    >
      <Space direction="vertical" size={16} style={{ width: "100%" }}>
        <Alert
          type="warning"
          showIcon
          message="This is the only time the full API key will be shown. Once closed, it cannot be retrieved again. Save it somewhere secure now."
          description="Only the key hash is stored; the plaintext cannot be recovered."
        />
        <div
          style={{
            padding: "16px",
            borderRadius: 8,
            background: "#f5f5f5",
            wordBreak: "break-all",
          }}
        >
          <Text code style={{ fontSize: 18, userSelect: "all" }}>
            {apiKey}
          </Text>
        </div>
        <div>
          <Button icon={<CopyOutlined />} onClick={handleCopy}>
            Copy Key
          </Button>
          <Paragraph
            type="secondary"
            style={{ margin: "8px 0 0", fontSize: 12 }}
          >
            Click the text above to select all; we recommend also saving it in a secure location such as a password manager.
          </Paragraph>
        </div>
      </Space>
    </Modal>
  );
}

export default CopyOnceModal;
