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

interface WarningItem {
    id: number;
    citizenid: string;
    reason: string;
    warned_by: string;
    created_at: string;
}

export default function Index({ warnings }: { warnings: { data: WarningItem[] } }) {
    const { data, setData, post, processing, errors, reset } = useForm({ citizenid: '', reason: '' });

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        post(route('admin.warnings.store'), { onSuccess: () => reset() });
    };

    return (
        <AdminLayout>
            <Head title="Warn Manager" />
            <h1 className="mb-6 text-2xl font-bold">Warn Manager</h1>

            <form onSubmit={submit} className="mb-8 grid gap-3 rounded-lg bg-gray-900 p-5 ring-1 ring-white/10 sm:grid-cols-2">
                <input
                    placeholder="Citizen ID"
                    value={data.citizenid}
                    onChange={(e) => setData('citizenid', e.target.value)}
                    className="rounded-md border-gray-700 bg-gray-800 text-white"
                />
                <input
                    placeholder="Reason"
                    value={data.reason}
                    onChange={(e) => setData('reason', 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-2 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"
                >
                    Issue warning
                </button>
            </form>

            <div className="divide-y divide-white/10 rounded-lg bg-gray-900 ring-1 ring-white/10">
                {warnings.data.map((w) => (
                    <div key={w.id} className="flex items-center justify-between px-5 py-3">
                        <div>
                            <p className="font-medium">{w.citizenid}</p>
                            <p className="text-xs text-gray-500">{w.reason} · by {w.warned_by}</p>
                        </div>
                        <button
                            onClick={() => confirm('Remove this warning?') && router.delete(route('admin.warnings.destroy', w.id))}
                            className="text-sm text-red-400 hover:text-red-300"
                        >
                            Remove
                        </button>
                    </div>
                ))}
                {warnings.data.length === 0 && <p className="px-5 py-4 text-gray-400">No warnings on record.</p>}
            </div>
        </AdminLayout>
    );
}
