import { AvatarCropModal } from '@app/components/settings/AvatarCropModal';
import SelectionStore from '@app/stores/SelectionStore';
import { SpaceManager } from '@brycord/matrix-client';
import { Button, Modal } from '@brycord/ui';
import { Camera } from '@phosphor-icons/react';
import { useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './CreateServerModal.module.css';

const ICON_MAX_SIZE = 10 * 1024 * 1024;

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

export function CreateServerModal({ isOpen, onClose }: CreateServerModalProps) {
	const navigate = useNavigate();
	const fileInputRef = useRef<HTMLInputElement>(null);

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

	const [iconPreview, setIconPreview] = useState<string | null>(null);
	const [iconFile, setIconFile] = useState<File | null>(null);
	const [cropCandidate, setCropCandidate] = useState<File | null>(null);

	const resetState = () => {
		setName('');
		setError(null);
		setIsCreating(false);
		if (iconPreview) URL.revokeObjectURL(iconPreview);
		setIconPreview(null);
		setIconFile(null);
		setCropCandidate(null);
	};

	const handleClose = () => {
		resetState();
		onClose();
	};

	const handleIconClick = () => {
		fileInputRef.current?.click();
	};

	const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
		const file = e.target.files?.[0];
		e.target.value = '';
		if (!file) return;
		if (!file.type.startsWith('image/')) {
			setError('Please select an image file.');
			return;
		}
		if (file.size > ICON_MAX_SIZE) {
			setError('Image must be under 10 MB.');
			return;
		}
		setError(null);
		setCropCandidate(file);
	};

	const handleCropped = (blob: Blob) => {
		const croppedFile = new File([blob], 'icon.png', {
			type: 'image/png',
			lastModified: Date.now(),
		});
		if (iconPreview) URL.revokeObjectURL(iconPreview);
		const url = URL.createObjectURL(blob);
		setIconPreview(url);
		setIconFile(croppedFile);
	};

	const handleSkipCrop = () => {
		const file = cropCandidate;
		if (!file) return;
		if (iconPreview) URL.revokeObjectURL(iconPreview);
		const url = URL.createObjectURL(file);
		setIconPreview(url);
		setIconFile(file);
	};

	const handleCreate = async () => {
		const trimmed = name.trim();
		if (!trimmed) return;
		setIsCreating(true);
		setError(null);

		try {
			const { spaceId, generalChannelId } = await SpaceManager.getInstance().createServer(
				trimmed,
				iconFile ?? undefined,
			);
			resetState();
			onClose();
			SelectionStore.selectServer(spaceId);
			SelectionStore.selectChannel(generalChannelId);
			navigate(`/channels/${spaceId}/${generalChannelId}`);
		} catch (err: any) {
			setError(err?.message || 'Failed to create server');
		} finally {
			setIsCreating(false);
		}
	};

	return (
		<>
			<Modal isOpen={isOpen} onClose={handleClose} title="Create a Community" width={440}>
				<div className={styles.content}>
					<p className={styles.description}>Create a community for you and your friends to chat.</p>

					<div className={styles.iconSection}>
						<button
							type="button"
							className={styles.iconUpload}
							onClick={handleIconClick}
							aria-label="Upload community icon"
						>
							{iconPreview ? (
								<img src={iconPreview} alt="Icon preview" className={styles.iconImage} />
							) : (
								<Camera size={32} weight="regular" className={styles.iconPlaceholder} />
							)}
						</button>
						<input
							ref={fileInputRef}
							type="file"
							accept="image/*"
							onChange={handleFileSelect}
							className={styles.hiddenInput}
						/>
						<div className={styles.iconHint}>
							<span className={styles.iconHintTitle}>Upload Icon</span>
							<span className={styles.iconHintDetail}>JPEG, PNG, WebP. Max 10MB. Recommended: 512x512px</span>
						</div>
					</div>

					<div className={styles.field}>
						<label className={styles.label}>COMMUNITY NAME</label>
						<input
							type="text"
							className={styles.input}
							value={name}
							onChange={(e) => setName(e.target.value)}
							placeholder="My Community"
							autoFocus
							onKeyDown={(e) => {
								if (e.key === 'Enter' && name.trim()) {
									void handleCreate();
								}
							}}
						/>
					</div>

					{error && <div className={styles.error}>{error}</div>}

					<div className={styles.actions}>
						<Button variant="ghost" onClick={handleClose}>
							Cancel
						</Button>
						<Button variant="primary" onClick={handleCreate} loading={isCreating} disabled={!name.trim()}>
							Create Community
						</Button>
					</div>
				</div>
			</Modal>

			<AvatarCropModal
				isOpen={cropCandidate !== null}
				onClose={() => setCropCandidate(null)}
				file={cropCandidate}
				onCropped={handleCropped}
				onSkipCrop={handleSkipCrop}
			/>
		</>
	);
}
