import * as React from 'react';
import { router } from '@inertiajs/react';
import {
    questionsApi,
    type QuestionOption,
    type QuestionPayload,
} from '../services/api';
import { ApiError } from '@/lib/ApiError';
import { Card, CardContent, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Textarea, Input } from '@/components/ui/input';
import { FormField } from '@/components/ui/form-field';
import { toast } from '@/components/ui/sonner';

const OPTION_KEYS: {
    key: keyof Pick<
        QuestionPayload,
        'option_a' | 'option_b' | 'option_c' | 'option_d'
    >;
    label: QuestionOption;
}[] = [
    { key: 'option_a', label: 'A' },
    { key: 'option_b', label: 'B' },
    { key: 'option_c', label: 'C' },
    { key: 'option_d', label: 'D' },
];

interface QuestionFormProps {
    questionId?: number;
    initial?: QuestionPayload;
}

/** Shared create/edit form for a quiz question: 4 options + which one is correct. */
export function QuestionForm({ questionId, initial }: QuestionFormProps) {
    const [form, setForm] = React.useState<QuestionPayload>(
        initial ?? {
            text: '',
            option_a: '',
            option_b: '',
            option_c: '',
            option_d: '',
            correct_option: 'A',
            active: true,
        },
    );
    const [errors, setErrors] = React.useState<Record<string, string>>({});
    const [submitting, setSubmitting] = React.useState(false);

    async function handleSubmit(e: React.FormEvent) {
        e.preventDefault();
        setSubmitting(true);
        setErrors({});
        try {
            if (questionId) {
                await questionsApi.update(questionId, form);
                toast.success('Question updated.');
            } else {
                await questionsApi.store(form);
                toast.success('Question created.');
            }
            router.visit('/admin/questions');
        } catch (err) {
            if (err instanceof ApiError && err.isValidationError) {
                const flat: Record<string, string> = {};
                for (const [k, v] of Object.entries(err.errors ?? {}))
                    flat[k] = v[0];
                setErrors(flat);
            } else {
                toast.error('Failed to save question.');
            }
        } finally {
            setSubmitting(false);
        }
    }

    return (
        <form onSubmit={handleSubmit}>
            <Card className="max-w-2xl">
                <CardContent className="space-y-4">
                    <FormField
                        label="Question text"
                        htmlFor="text"
                        required
                        error={errors.text}
                    >
                        <Textarea
                            id="text"
                            rows={3}
                            required
                            value={form.text}
                            onChange={(e) =>
                                setForm({ ...form, text: e.target.value })
                            }
                        />
                    </FormField>

                    <div className="grid gap-4 sm:grid-cols-2">
                        {OPTION_KEYS.map(({ key, label }) => (
                            <FormField
                                key={key}
                                label={`Option ${label}`}
                                htmlFor={key}
                                required
                                error={errors[key]}
                            >
                                <Input
                                    id={key}
                                    required
                                    value={form[key]}
                                    onChange={(e) =>
                                        setForm({
                                            ...form,
                                            [key]: e.target.value,
                                        })
                                    }
                                />
                            </FormField>
                        ))}
                    </div>

                    <FormField
                        label="Correct option"
                        group
                        required
                        error={errors.correct_option}
                    >
                        <div className="flex gap-4">
                            {OPTION_KEYS.map(({ label }) => (
                                <label
                                    key={label}
                                    className="flex items-center gap-1.5 text-sm text-(--color-ink)"
                                >
                                    <input
                                        type="radio"
                                        name="correct_option"
                                        value={label}
                                        checked={form.correct_option === label}
                                        onChange={() =>
                                            setForm({
                                                ...form,
                                                correct_option: label,
                                            })
                                        }
                                    />
                                    {label}
                                </label>
                            ))}
                        </div>
                    </FormField>

                    <label className="flex items-center gap-2 text-sm text-(--color-ink)">
                        <input
                            type="checkbox"
                            checked={form.active}
                            onChange={(e) =>
                                setForm({ ...form, active: e.target.checked })
                            }
                        />
                        Active (shown in the quiz)
                    </label>
                </CardContent>
                <CardFooter>
                    <Button
                        type="button"
                        variant="outline"
                        onClick={() => router.visit('/admin/questions')}
                    >
                        Cancel
                    </Button>
                    <Button type="submit" loading={submitting}>
                        {questionId ? 'Save changes' : 'Create question'}
                    </Button>
                </CardFooter>
            </Card>
        </form>
    );
}
