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

const questions = [
    'Why do you want to join this server?',
    'Describe what roleplay means to you.',
    'How would you handle fail-RP from another player?',
];

interface Props {
    existingApplication: { status: string } | null;
}

export default function WhitelistApply({ existingApplication }: Props) {
    const { data, setData, post, processing, errors } = useForm<{ answers: Record<string, string> }>({
        answers: Object.fromEntries(questions.map((q) => [q, ''])),
    });

    const submit: FormEventHandler = (e) => {
        e.preventDefault();
        post(route('whitelist.store'));
    };

    if (existingApplication && existingApplication.status === 'pending') {
        return (
            <AppLayout>
                <Head title="Whitelist application" />
                <p className="rounded-md bg-gray-900 p-6 text-gray-300 ring-1 ring-white/10">
                    Your application is pending review.
                </p>
            </AppLayout>
        );
    }

    return (
        <AppLayout>
            <Head title="Apply for whitelist" />
            <h1 className="mb-6 text-2xl font-bold">Whitelist application</h1>

            <form onSubmit={submit} className="space-y-4 rounded-lg bg-gray-900 p-6 ring-1 ring-white/10">
                {questions.map((q) => (
                    <div key={q}>
                        <label className="mb-1 block text-sm text-gray-300">{q}</label>
                        <textarea
                            rows={3}
                            value={data.answers[q]}
                            onChange={(e) => setData('answers', { ...data.answers, [q]: e.target.value })}
                            className="w-full rounded-md border-gray-700 bg-gray-800 text-white"
                        />
                    </div>
                ))}
                {errors.answers && <p className="text-sm text-red-400">{errors.answers}</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"
                >
                    Submit application
                </button>
            </form>
        </AppLayout>
    );
}
