import { useEffect, useState } from 'react';
import { useMutation } from 'convex/react';
import { Hash, SpeakerHigh } from '@phosphor-icons/react';
import { Modal, Button } from '@discord-clone/ui';
import { api } from '../../../../../convex/_generated/api';
import styles from './CreateChannelModal.module.css';

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

/**
 * CreateChannelModal — Convex-backed channel creation.
 * Collects a name, a text/voice type, and an optional topic, then calls
 * `api.channels.create` and closes.
 */
export function CreateChannelModal({ isOpen, onClose }: CreateChannelModalProps) {
	const createChannel = useMutation(api.channels.create);

	const [name, setName] = useState('');
	const [channelType, setChannelType] = useState<'text' | 'voice'>('text');
	const [topic, setTopic] = useState('');
	const [loading, setLoading] = useState(false);
	const [error, setError] = useState<string | null>(null);

	useEffect(() => {
		if (isOpen) {
			setName('');
			setChannelType('text');
			setTopic('');
			setLoading(false);
			setError(null);
		}
	}, [isOpen]);

	const handleSubmit = async (e: React.FormEvent) => {
		e.preventDefault();
		const trimmed = name.trim();
		if (!trimmed) return;

		setLoading(true);
		setError(null);
		try {
			await createChannel({
				name: trimmed,
				type: channelType,
				topic: topic.trim() || undefined,
			});
			onClose();
		} catch (err: any) {
			setError(err?.message || 'Failed to create channel');
		} finally {
			setLoading(false);
		}
	};

	return (
		<Modal.Root isOpen={isOpen} onClose={onClose} size="small">
			<Modal.Header title="Create Channel" onClose={onClose} />
			<Modal.Content>
				<form id="create-channel-form" onSubmit={handleSubmit} className={styles.body}>
					<div className={styles.typeSelector}>
						<label className={styles.label}>CHANNEL TYPE</label>
						<div className={styles.typeOptions}>
							<button
								type="button"
								className={`${styles.typeOption} ${
									channelType === 'text' ? styles.typeOptionActive : ''
								}`}
								onClick={() => setChannelType('text')}
							>
								<Hash size={20} weight="bold" />
								<span>Text</span>
							</button>
							<button
								type="button"
								className={`${styles.typeOption} ${
									channelType === 'voice' ? styles.typeOptionActive : ''
								}`}
								onClick={() => setChannelType('voice')}
							>
								<SpeakerHigh size={20} />
								<span>Voice</span>
							</button>
						</div>
					</div>

					<div className={styles.field}>
						<label className={styles.label}>CHANNEL NAME</label>
						<input
							className={styles.input}
							value={name}
							onChange={(e) => setName(e.target.value)}
							placeholder="new-channel"
							autoFocus
						/>
					</div>

					<div className={styles.field}>
						<label className={styles.label}>TOPIC (OPTIONAL)</label>
						<input
							className={styles.input}
							value={topic}
							onChange={(e) => setTopic(e.target.value)}
							placeholder="What's this channel about?"
						/>
					</div>

					{error && (
						<div className={styles.field} style={{ color: 'var(--status-danger)', fontSize: '0.875rem' }}>
							{error}
						</div>
					)}
				</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-channel-form"
					loading={loading}
					disabled={!name.trim()}
				>
					Create Channel
				</Button>
			</Modal.Footer>
		</Modal.Root>
	);
}
