/**
 * EditAttachmentModal — opened from a PendingAttachmentCard's
 * "Edit" hover button. Lets the user rename the outgoing file,
 * add an alt-text description, and toggle the Mark-as-Spoiler
 * flag before sending.
 *
 * The Alt Text Description field is hidden for audio attachments
 * per the user's spec — audio doesn't carry a visual payload so
 * the accessibility angle doesn't apply.
 *
 * Saving writes the edits back to PendingAttachmentStore via
 * `updateAttachment`, which re-renders the affected card
 * reactively without any prop wiring.
 */
import { useEffect, useState } from 'react';
import { Modal } from '@brycord/ui';
import PendingAttachmentStore, {
	type PendingAttachment,
} from '@app/stores/PendingAttachmentStore';
import styles from './EditAttachmentModal.module.css';

const ALT_TEXT_MAX = 4096;

interface EditAttachmentModalProps {
	isOpen: boolean;
	onClose: () => void;
	channelId: string;
	attachment: PendingAttachment | null;
}

export function EditAttachmentModal({
	isOpen,
	onClose,
	channelId,
	attachment,
}: EditAttachmentModalProps) {
	const [filename, setFilename] = useState('');
	const [altText, setAltText] = useState('');
	const [isSpoiler, setIsSpoiler] = useState(false);

	// Hydrate the form every time the modal opens on a (possibly
	// different) attachment. Without this re-sync, the user's last
	// edit on a previous card would leak into the next one.
	useEffect(() => {
		if (!isOpen || !attachment) return;
		setFilename(attachment.filename);
		setAltText(attachment.altText);
		setIsSpoiler(attachment.isSpoiler);
	}, [isOpen, attachment]);

	if (!attachment) return null;

	const hideAltText = attachment.kind === 'audio';

	const handleSave = () => {
		PendingAttachmentStore.updateAttachment(channelId, attachment.id, {
			filename: filename.trim() || attachment.file.name,
			altText: altText.trim(),
			isSpoiler,
		});
		onClose();
	};

	return (
		<Modal.Root isOpen={isOpen} onClose={onClose} size="small">
			<Modal.Header title="Edit Attachment" onClose={onClose} />
			<Modal.Content>
				<div className={styles.body}>
					<div className={styles.field}>
						<label className={styles.label} htmlFor="edit-att-filename">
							Filename
						</label>
						<input
							id="edit-att-filename"
							type="text"
							className={styles.input}
							value={filename}
							onChange={(e) => setFilename(e.target.value)}
							autoFocus
						/>
					</div>

					{!hideAltText && (
						<div className={styles.field}>
							<div className={styles.labelRow}>
								<label className={styles.label} htmlFor="edit-att-alt">
									Alt Text Description
								</label>
								<span className={styles.counter}>
									{altText.length}/{ALT_TEXT_MAX}
								</span>
							</div>
							<textarea
								id="edit-att-alt"
								className={styles.textarea}
								placeholder="Describe this media for screen readers"
								value={altText}
								onChange={(e) =>
									setAltText(e.target.value.slice(0, ALT_TEXT_MAX))
								}
								rows={3}
							/>
						</div>
					)}

					<div className={styles.spoilerRow}>
						<label className={styles.spoilerLabel} htmlFor="edit-att-spoiler">
							Mark as Spoiler
						</label>
						<button
							id="edit-att-spoiler"
							type="button"
							className={`${styles.toggle} ${
								isSpoiler ? styles.toggleOn : ''
							}`}
							onClick={() => setIsSpoiler((v) => !v)}
							aria-pressed={isSpoiler}
							aria-label="Mark as spoiler"
						>
							<span className={styles.toggleThumb} />
						</button>
					</div>

					<div className={styles.actions}>
						<button
							type="button"
							className={styles.secondaryButton}
							onClick={onClose}
						>
							Cancel
						</button>
						<button
							type="button"
							className={styles.primaryButton}
							onClick={handleSave}
						>
							Save
						</button>
					</div>
				</div>
			</Modal.Content>
		</Modal.Root>
	);
}
