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

interface JobItem {
    name: string;
    label: string;
    grades: { name: string; label: string; level: number; salary: number }[];
}

export default function Index({ jobs }: { jobs: JobItem[] }) {
    const { data, setData, post, processing, errors, reset } = useForm({
        name: '',
        label: '',
        grades: [] as { name: string; label: string; level: number; salary: number }[],
    });

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

    return (
        <AdminLayout>
            <Head title="Job Manager" />
            <h1 className="mb-6 text-2xl font-bold">Job 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="Job name (e.g. police)"
                    value={data.name}
                    onChange={(e) => setData('name', e.target.value)}
                    className="rounded-md border-gray-700 bg-gray-800 text-white"
                />
                <input
                    placeholder="Label (e.g. Police Department)"
                    value={data.label}
                    onChange={(e) => setData('label', 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"
                >
                    Save job
                </button>
            </form>

            <div className="divide-y divide-white/10 rounded-lg bg-gray-900 ring-1 ring-white/10">
                {jobs.map((job) => (
                    <div key={job.name} className="px-5 py-3">
                        <p className="font-medium">{job.label}</p>
                        <p className="text-xs text-gray-500">{job.name} · {job.grades?.length ?? 0} grades</p>
                    </div>
                ))}
                {jobs.length === 0 && <p className="px-5 py-4 text-gray-400">No jobs mirrored to the database yet.</p>}
            </div>
        </AdminLayout>
    );
}
