import { Button } from '@/Components/ui/button';
import { Field, Input, Textarea } from '@/Components/ui/field';
import { useForm } from '@inertiajs/react';
import { FormEventHandler } from 'react';

type Mine = { title: string | null; body: string; contains_spoilers: boolean } | null;

export default function ReviewForm({ slug, review, verified }: { slug: string; review: Mine; verified: boolean }) {
    const { data, setData, put, delete: destroy, processing, errors } = useForm({
        title: review?.title ?? '',
        body: review?.body ?? '',
        contains_spoilers: review?.contains_spoilers ?? false,
    });

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        put(route('games.review.store', slug), { preserveScroll: true });
    };

    if (!verified) {
        return <p className="rounded-lg border border-dashed border-border p-4 text-sm text-muted-foreground">Verify your email to write a review.</p>;
    }

    return (
        <form onSubmit={submit} className="space-y-3">
            <Field label="Title (optional)" htmlFor="rv-title" error={errors.title}>
                <Input id="rv-title" value={data.title} maxLength={120} onChange={(e) => setData('title', e.target.value)} placeholder="A line that sums it up" />
            </Field>
            <Field label="Your review" htmlFor="rv-body" error={errors.body} hint={`${data.body.length}/5000 · at least 20 characters`}>
                <Textarea id="rv-body" rows={5} value={data.body} onChange={(e) => setData('body', e.target.value)} aria-invalid={!!errors.body} placeholder="What stayed with you?" />
            </Field>
            <label className="flex items-center gap-2 text-sm text-muted-foreground">
                <input type="checkbox" checked={data.contains_spoilers} onChange={(e) => setData('contains_spoilers', e.target.checked)} className="size-4 rounded border-input bg-card text-primary" />
                Contains spoilers
            </label>
            <div className="flex items-center gap-2">
                <Button type="submit" loading={processing}>{review ? 'Update review' : 'Post review'}</Button>
                {review && (
                    <Button type="button" variant="ghost" onClick={() => confirm('Delete your review?') && destroy(route('games.review.destroy', slug), { preserveScroll: true })}>
                        Delete
                    </Button>
                )}
            </div>
        </form>
    );
}
