import { router, usePage } from '@inertiajs/react';
import { useState, type FormEvent } from 'react';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';

type EditableEvent = {
    id: number;
    title: string;
    description?: string | null;
    banner_url?: string | null;
};

export default function AdminEventContentDialog({
    event,
    onClose,
}: {
    event: EditableEvent;
    onClose: () => void;
}) {
    const [processing, setProcessing] = useState(false);
    const [hasReplacement, setHasReplacement] = useState(false);
    const page = usePage();
    const errors =
        (page.props as typeof page.props & { errors?: Record<string, string> })
            .errors ?? {};

    function submit(formEvent: FormEvent<HTMLFormElement>) {
        formEvent.preventDefault();
        setProcessing(true);
        router.post(
            `/admin/events/${event.id}/content`,
            new FormData(formEvent.currentTarget),
            {
                forceFormData: true,
                preserveScroll: true,
                onFinish: () => setProcessing(false),
                onSuccess: onClose,
            },
        );
    }

    return (
        <Dialog open onOpenChange={(open) => !open && onClose()}>
            <DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-xl">
                <DialogHeader>
                    <DialogTitle>Edit {event.title}</DialogTitle>
                    <DialogDescription>
                        The image and race brief appear on the public event
                        pages.
                    </DialogDescription>
                </DialogHeader>
                <form onSubmit={submit} className="space-y-4">
                    {Object.keys(errors).length > 0 && (
                        <div
                            role="alert"
                            className="rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-sm text-rose-800"
                        >
                            {Object.values(errors).join(' ')}
                        </div>
                    )}
                    {event.banner_url && (
                        <img
                            src={event.banner_url}
                            alt={`Current image for ${event.title}`}
                            className="aspect-[16/7] w-full rounded-xl object-cover"
                        />
                    )}
                    <label className="grid gap-1.5 text-sm font-semibold text-slate-700">
                        Event description
                        <textarea
                            name="description"
                            rows={7}
                            maxLength={5000}
                            defaultValue={event.description ?? ''}
                            placeholder="Write the race brief. Leave a blank line between paragraphs."
                            className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm font-normal outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-100"
                        />
                        <span className="text-xs font-normal text-slate-500">
                            Blank lines become paragraph breaks on the event
                            page.
                        </span>
                    </label>
                    <label className="grid gap-1.5 text-sm font-semibold text-slate-700">
                        {event.banner_url
                            ? 'Replace event image'
                            : 'Add event image'}
                        <input
                            name="banner"
                            type="file"
                            accept="image/jpeg,image/png,image/webp"
                            onChange={(changeEvent) =>
                                setHasReplacement(
                                    Boolean(changeEvent.target.files?.length),
                                )
                            }
                            className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm font-normal file:mr-3 file:rounded-lg file:border-0 file:bg-slate-100 file:px-3 file:py-1.5 focus-visible:outline-2 focus-visible:outline-blue-500"
                        />
                        <span className="text-xs font-normal text-slate-500">
                            JPEG, PNG or WebP, up to 5 MB.
                        </span>
                    </label>
                    {event.banner_url && (
                        <label className="flex items-center gap-2 text-sm text-slate-700">
                            <input
                                type="checkbox"
                                name="remove_banner"
                                value="1"
                                disabled={hasReplacement}
                                className="size-4 rounded border-slate-300"
                            />
                            Remove current image
                        </label>
                    )}
                    <DialogFooter>
                        <button
                            type="button"
                            onClick={onClose}
                            className="h-10 rounded-lg border border-slate-200 px-4 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                        >
                            Cancel
                        </button>
                        <button
                            disabled={processing}
                            className="h-10 rounded-lg bg-slate-900 px-4 text-sm font-semibold text-white hover:bg-slate-700 disabled:opacity-60"
                        >
                            {processing ? 'Saving…' : 'Save event content'}
                        </button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}
