/**
 * CreateCategoryModal — Convex-backed category creation.
 *
 * (File historically named CategorySettingsModal; repurposed for the
 * minimal "create category" flow. The export is CreateCategoryModal.)
 */
import { useEffect, useState } from 'react';
import { useMutation } from 'convex/react';
import { Modal, Button } from '@discord-clone/ui';
import { api } from '../../../../../convex/_generated/api';
import styles from './CategorySettingsModal.module.css';

const NAME_MAX = 100;

interface CreateCategoryModalProps {
	isOpen: boolean;
	onClose: () => void;
}

export function CreateCategoryModal({ isOpen, onClose }: CreateCategoryModalProps) {
	const createCategory = useMutation(api.categories.create);

	const [name, setName] = useState('');
	const [saving, setSaving] = useState(false);
	const [error, setError] = useState<string | null>(null);

	useEffect(() => {
		if (isOpen) {
			setName('');
			setSaving(false);
			setError(null);
		}
	}, [isOpen]);

	const trimmed = name.trim();
	const canSave = trimmed.length > 0 && trimmed.length <= NAME_MAX && !saving;

	const handleSubmit = async (e: React.FormEvent) => {
		e.preventDefault();
		if (!canSave) return;
		setSaving(true);
		setError(null);
		try {
			await createCategory({ name: trimmed });
			onClose();
		} catch (err: any) {
			setError(err?.message || 'Failed to create category.');
		} finally {
			setSaving(false);
		}
	};

	return (
		<Modal.Root isOpen={isOpen} onClose={onClose} size="small">
			<Modal.Header title="Create Category" onClose={onClose} />
			<Modal.Content>
				<form id="create-category-form" onSubmit={handleSubmit} className={styles.body}>
					<fieldset className={styles.field} disabled={saving}>
						<label className={styles.fieldLabel} htmlFor="create-category-name">
							Category Name
						</label>
						<input
							id="create-category-name"
							type="text"
							className={styles.fieldInput}
							value={name}
							onChange={(e) => setName(e.target.value)}
							maxLength={NAME_MAX}
							placeholder="New Category"
							autoFocus
						/>
						<div className={styles.fieldHintRow}>
							<span className={styles.fieldCounter}>
								{trimmed.length}/{NAME_MAX}
							</span>
						</div>
					</fieldset>

					{error && <p className={`${styles.status} ${styles.statusError}`}>{error}</p>}
				</form>
			</Modal.Content>
			<Modal.Footer>
				<Button variant="secondary" size="sm" onClick={onClose} type="button">
					Cancel
				</Button>
				<Button
					variant="primary"
					size="sm"
					type="submit"
					form="create-category-form"
					loading={saving}
					disabled={!canSave}
				>
					Create Category
				</Button>
			</Modal.Footer>
		</Modal.Root>
	);
}
