/**
 * MessageInspectModal — debug/dev view that dumps the raw Convex message
 * document behind a rendered message. Callers pass the already-decrypted
 * message object (the same shape that flows through Messages /
 * MessageGroup props), and this modal pretty-prints the document plus
 * a handful of broken-out fields that are commonly useful when
 * debugging rendering issues.
 */
import { useMemo, useState } from 'react';
import { Copy, CheckCircle } from '@phosphor-icons/react';
import { Modal, Button } from '@discord-clone/ui';
import styles from './MessageInspectModal.module.css';

interface MessageInspectModalProps {
	isOpen: boolean;
	onClose: () => void;
	message: Record<string, unknown> | null;
}

function safeStringify(value: unknown): string {
	try {
		return JSON.stringify(value, null, 2);
	} catch {
		return String(value);
	}
}

export function MessageInspectModal({ isOpen, onClose, message }: MessageInspectModalProps) {
	const [copied, setCopied] = useState<string | null>(null);

	const summary = useMemo(() => {
		if (!message) return null;
		const m = message as any;
		return {
			id: String(m._id ?? ''),
			channelId: String(m.channelId ?? ''),
			senderId: String(m.senderId ?? ''),
			timestamp: typeof m._creationTime === 'number' ? m._creationTime : Number(m.createdAt ?? 0),
			content: typeof m.decryptedContent === 'string' ? m.decryptedContent : null,
			attachments: m.attachments ?? null,
			raw: m,
		};
	}, [message]);

	const handleCopy = (label: string, text: string) => {
		navigator.clipboard.writeText(text).then(
			() => {
				setCopied(label);
				setTimeout(() => setCopied((c) => (c === label ? null : c)), 1500);
			},
			() => {},
		);
	};

	if (!isOpen) return null;

	return (
		<Modal.Root isOpen={isOpen} onClose={onClose} size="large">
			<Modal.Header title="Inspect Message" onClose={onClose} />
			<Modal.Content className={styles.content}>
				{!summary ? (
					<div className={styles.emptyState}>No message selected.</div>
				) : (
					<div className={styles.sections}>
						<Section
							label="Message ID"
							value={summary.id}
							onCopy={handleCopy}
							copied={copied}
						/>
						<Section
							label="Channel ID"
							value={summary.channelId}
							onCopy={handleCopy}
							copied={copied}
						/>
						<Section
							label="Sender ID"
							value={summary.senderId}
							onCopy={handleCopy}
							copied={copied}
						/>
						<Section
							label="Timestamp"
							value={`${new Date(summary.timestamp).toISOString()}  (${summary.timestamp})`}
							onCopy={handleCopy}
							copied={copied}
						/>

						{summary.content !== null && (
							<JsonBlock
								label="Decrypted Content"
								value={summary.content}
								onCopy={handleCopy}
								copied={copied}
								accent
							/>
						)}

						{summary.attachments && (
							<JsonBlock
								label="Attachments"
								value={safeStringify(summary.attachments)}
								onCopy={handleCopy}
								copied={copied}
							/>
						)}

						<JsonBlock
							label="Raw Document"
							value={safeStringify(summary.raw)}
							onCopy={handleCopy}
							copied={copied}
						/>
					</div>
				)}
			</Modal.Content>
			<Modal.Footer>
				<Button variant="secondary" onClick={onClose}>
					Close
				</Button>
			</Modal.Footer>
		</Modal.Root>
	);
}

function Section({
	label,
	value,
	onCopy,
	copied,
}: {
	label: string;
	value: string;
	onCopy: (label: string, text: string) => void;
	copied: string | null;
}) {
	return (
		<div className={styles.section}>
			<div className={styles.sectionHeader}>
				<span className={styles.sectionLabel}>{label}</span>
				<button
					type="button"
					className={styles.copyButton}
					onClick={() => onCopy(label, value)}
					aria-label={`Copy ${label}`}
				>
					{copied === label ? <CheckCircle size={14} weight="fill" /> : <Copy size={14} weight="fill" />}
				</button>
			</div>
			<div className={styles.sectionValue}>{value}</div>
		</div>
	);
}

function JsonBlock({
	label,
	value,
	onCopy,
	copied,
	accent,
}: {
	label: string;
	value: string;
	onCopy: (label: string, text: string) => void;
	copied: string | null;
	accent?: boolean;
}) {
	return (
		<div className={`${styles.section} ${accent ? styles.sectionAccent : ''}`}>
			<div className={styles.sectionHeader}>
				<span className={styles.sectionLabel}>{label}</span>
				<button
					type="button"
					className={styles.copyButton}
					onClick={() => onCopy(label, value)}
					aria-label={`Copy ${label}`}
				>
					{copied === label ? <CheckCircle size={14} weight="fill" /> : <Copy size={14} weight="fill" />}
				</button>
			</div>
			<pre className={styles.jsonBlock}>{value}</pre>
		</div>
	);
}
