import { useState } from "react";
import { logError } from "../../utils/logger";

interface UserIdCopyProps {
	userId: string;
}

export function UserIdCopy({ userId }: UserIdCopyProps): React.JSX.Element {
	const [copiedUserId, setCopiedUserId] = useState(false);
	const [showTooltip, setShowTooltip] = useState(false);

	const handleCopyUserId = async () => {
		if (!userId) {
			return;
		}

		try {
			// Try modern Clipboard API first (but only if it's truly available)
			if (
				navigator.clipboard &&
				navigator.clipboard.writeText &&
				window.isSecureContext
			) {
				try {
					await navigator.clipboard.writeText(userId);
					setCopiedUserId(true);
					setTimeout(() => setCopiedUserId(false), 2000);
					return;
				} catch (clipboardError) {
					// Fall through to execCommand
				}
			}

			// Fallback: Use execCommand (works in most webviews)
			// @ts-ignore - Suppress deprecation warning for fallback
			const textArea = document.createElement("textarea");
			textArea.value = userId;
			textArea.className = "kiro-clipboard-textarea";

			// Append to modal dialog to work within focus trap
			const modal = document.querySelector("#account-dashboard-modal");
			const container = modal || document.body;
			container.appendChild(textArea);

			textArea.focus();
			textArea.select();
			// @ts-ignore - Suppress deprecation warning for fallback
			const successful = document.execCommand("copy");

			container.removeChild(textArea);

			if (successful) {
				setCopiedUserId(true);
				setTimeout(() => setCopiedUserId(false), 2000);
			} else {
				logError("Copy failed", new Error("Both clipboard methods failed"));
			}
		} catch (error) {
			logError("Copy failed", error as Error);
		}
	};

	return (
		<div className="kiro-user-id">
			<div className="kiro-user-id-container">
				<div className="kiro-modal-link">
					<a
						className="kiro-text-secondary kiro-user-id-text"
						onClick={handleCopyUserId}
						onMouseEnter={() => setShowTooltip(true)}
						onMouseLeave={() => setShowTooltip(false)}
						data-testid="user-id"
					>
						{copiedUserId ? "User ID copied" : "User ID"}
					</a>
					{copiedUserId && (
						<span className="kiro-user-id-success-checkmark">✓</span>
					)}
					{showTooltip && !copiedUserId && (
						<div className="kiro-user-id-tooltip">{userId}</div>
					)}
				</div>
			</div>
			{!copiedUserId && (
				<button
					onClick={(e) => {
						e.stopPropagation();
						handleCopyUserId();
					}}
					className="kiro-user-id-copy-button"
					title="Copy User ID"
					data-testid="copy-user-id-button"
					type="button"
				>
					<svg
						width="12"
						height="12"
						viewBox="0 0 24 24"
						fill="none"
						className="kiro-text-secondary"
					>
						<rect
							x="9"
							y="9"
							width="13"
							height="13"
							rx="2"
							ry="2"
							stroke="currentColor"
							strokeWidth="2"
						/>
						<path
							d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"
							stroke="currentColor"
							strokeWidth="2"
						/>
					</svg>
				</button>
			)}
		</div>
	);
}
