import { Head, useForm } from '@inertiajs/react';
import { FormEventHandler } from 'react';
import AdminLayout from '@/Layouts/AdminLayout';

export default function Index() {
    const { data, setData, post, processing, errors, reset } = useForm({
        citizen_id: '',
        item_name: '',
        amount: '1',
    });

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        post(route('admin.items.grant'), { onSuccess: () => reset('item_name', 'amount') });
    };

    return (
        <AdminLayout>
            <Head title="Item Manager" />
            <h1 className="mb-2 text-2xl font-bold">Item Manager</h1>
            <p className="mb-6 text-sm text-gray-400">
                Grants an item directly to a character&apos;s inventory. Item names must match the internal name
                defined in your framework&apos;s item catalog (e.g. qb-core/shared/items.lua).
            </p>

            <form onSubmit={submit} className="grid gap-3 rounded-lg bg-gray-900 p-5 ring-1 ring-white/10 sm:grid-cols-3">
                <input
                    placeholder="Citizen ID"
                    value={data.citizen_id}
                    onChange={(e) => setData('citizen_id', e.target.value)}
                    className="rounded-md border-gray-700 bg-gray-800 text-white"
                />
                <input
                    placeholder="Item internal name (e.g. bread)"
                    value={data.item_name}
                    onChange={(e) => setData('item_name', e.target.value)}
                    className="rounded-md border-gray-700 bg-gray-800 text-white"
                />
                <input
                    type="number"
                    min={1}
                    value={data.amount}
                    onChange={(e) => setData('amount', e.target.value)}
                    className="rounded-md border-gray-700 bg-gray-800 text-white"
                />
                {Object.values(errors).map((err, i) => (
                    <p key={i} className="sm:col-span-3 text-sm text-red-400">{err}</p>
                ))}
                <button
                    disabled={processing}
                    className="rounded-md bg-brand-600 px-4 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-50 sm:col-span-3"
                >
                    Grant item
                </button>
            </form>
        </AdminLayout>
    );
}
