import InputError from '@/components/input-error';
import { Button, buttonVariants } from '@/components/ui/button';
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import ImageUpload from '@/components/ui/imageUpload';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem } from '@/types';
import { Head, Link, useForm } from '@inertiajs/react';
import { FormEventHandler, useRef } from 'react';
import ReactQuill from 'react-quill-new';
import 'react-quill-new/dist/quill.snow.css';

interface SubTopicItem {
    id: number;
    name: string;
    topic: {
        id: number;
        name: string;
    };
}

type OptionInput = {
    option: string;
    is_correct: boolean;
};

type CreateQuestionForm = {
    question: string;
    type: 'single_choice' | 'multiple_choice';
    sub_topic_id: number | string;
    explanation: string;
    image: string;
    options: OptionInput[];
};

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Questions', href: '/question' },
    { title: 'Create', href: '/question/create' },
];

export default function Create({ subTopics }: { subTopics: SubTopicItem[] }) {
    const questionInput = useRef<HTMLInputElement>(null);

    const { data, setData, errors, post, reset, processing } = useForm<CreateQuestionForm>({
        question: '',
        type: 'single_choice',
        sub_topic_id: '',
        explanation: '',
        image: '',
        options: [
            { option: '', is_correct: false },
            { option: '', is_correct: false },
            { option: '', is_correct: false },
            { option: '', is_correct: false },
            { option: '', is_correct: false },
        ],
    });

    const handleOptionChange = (index: number, field: keyof OptionInput, val: string | boolean) => {
        const newOptions = [...data.options];

        if (field === 'is_correct') {
            if (data.type === 'single_choice') {
                newOptions.forEach((o, i) => {
                    o.is_correct = i === index;
                });
            } else {
                newOptions[index].is_correct = val as boolean;
            }
        } else {
            newOptions[index].option = val as string;
        }

        setData('options', newOptions);
    };

    const createQuestion: FormEventHandler = (e) => {
        e.preventDefault();

        const correctCount = data.options.filter((opt) => opt.is_correct).length;

        if (correctCount < 1) {
            alert('Please select at least one correct option.');
            return;
        }

        post(route('question.store'), {
            preserveScroll: true,
            onSuccess: () => reset(),
            onError: (errs) => {
                if (errs.question) {
                    questionInput.current?.focus();
                }
            },
        });
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Question Create" />

            <div className="m-5">
                <div className="flex">
                    <Link className={buttonVariants({ variant: 'default', className: 'mb-2 ml-auto' })} href={route('question.index')}>
                        Question List
                    </Link>
                </div>

                <form onSubmit={createQuestion}>
                    {/* Question Card */}
                    <Card className="mb-6">
                        <CardHeader>
                            <CardTitle>Create Question</CardTitle>
                        </CardHeader>

                        <CardContent>
                            <div className="grid w-full items-center gap-4">
                                {/* Question */}
                                <div className="flex flex-col space-y-1.5">
                                    <Label htmlFor="question">Question</Label>
                                    <Input
                                        id="question"
                                        ref={questionInput}
                                        value={data.question}
                                        onChange={(e) => setData('question', e.target.value)}
                                        placeholder="Enter the question"
                                        disabled={processing}
                                    />
                                    <InputError message={errors.question} />
                                </div>

                                <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                                    {/* Type */}
                                    <div className="flex flex-col space-y-1.5">
                                        <Label>Question Type</Label>
                                        <select
                                            value={data.type}
                                            onChange={(e) => setData('type', e.target.value as any)}
                                            className="border-input bg-background flex h-10 w-full rounded-md border px-3 py-2 text-sm"
                                            disabled={processing}
                                        >
                                            <option value="single_choice">Single Choice</option>
                                            <option value="multiple_choice">Multiple Choice</option>
                                        </select>
                                        <InputError message={errors.type} />
                                    </div>

                                    {/* Sub Topic */}
                                    <div className="flex flex-col space-y-1.5">
                                        <Label>Sub Topic</Label>
                                        <select
                                            value={data.sub_topic_id}
                                            onChange={(e) => setData('sub_topic_id', e.target.value)}
                                            className="border-input bg-background flex h-10 w-full rounded-md border px-3 py-2 text-sm"
                                            disabled={processing}
                                        >
                                            <option value="">Select Sub Topic</option>
                                            {subTopics.map((st) => (
                                                <option key={st.id} value={st.id}>
                                                    {st.topic?.name} → {st.name}
                                                </option>
                                            ))}
                                        </select>
                                        <InputError message={errors.sub_topic_id} />
                                    </div>
                                </div>
                                <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                                    {/* Explanation */}
                                    <div className="flex flex-col space-y-1.5">
                                        <Label>Explanation</Label>
                                        <div className="mt-2 rounded-md bg-white pb-10">
                                            <ReactQuill
                                                theme="snow"
                                                value={data.explanation}
                                                onChange={(content) => setData('explanation', content)}
                                                className="h-[200px]"
                                                readOnly={processing}
                                            />
                                        </div>
                                        <InputError message={errors.explanation} />
                                    </div>

                                    {/* Image Upload */}
                                    <div className="flex flex-col space-y-1.5">
                                        <ImageUpload
                                            label="Upload Image"
                                            value={data.image}
                                            existingImageUrl={data.image ? `/${data.image}` : null}
                                            onChange={(file) => setData('image', file)}
                                        />
                                        <InputError message={errors.image as any} />
                                    </div>
                                </div>
                                {/* Options */}
                                <div className="mt-4 rounded-md border p-4">
                                    <h3 className="mb-4 text-lg font-semibold">Options</h3>

                                    <div className="space-y-3">
                                        {data.options.map((opt, index) => (
                                            <div key={index} className="flex items-center gap-2">
                                                <span className="w-6 text-sm font-medium">{index + 1}.</span>

                                                <Input
                                                    value={opt.option}
                                                    onChange={(e) => handleOptionChange(index, 'option', e.target.value)}
                                                    placeholder={`Option ${index + 1}`}
                                                    disabled={processing}
                                                />

                                                <label className="flex items-center gap-1">
                                                    <input
                                                        type={data.type === 'single_choice' ? 'radio' : 'checkbox'}
                                                        name="correct_option"
                                                        checked={opt.is_correct}
                                                        onChange={(e) => handleOptionChange(index, 'is_correct', e.target.checked)}
                                                    />
                                                    Correct
                                                </label>
                                            </div>
                                        ))}
                                    </div>

                                    <InputError message={(errors as any).options} />
                                </div>
                            </div>
                        </CardContent>

                        <CardFooter className="flex justify-between">
                            <Link className={buttonVariants({ variant: 'default' })} href={route('question.index')}>
                                Cancel
                            </Link>

                            <div className="space-x-2">
                                <Button type="button" variant="outline" onClick={() => reset()}>
                                    Reset
                                </Button>

                                <Button type="submit" disabled={processing}>
                                    Create
                                </Button>
                            </div>
                        </CardFooter>
                    </Card>
                </form>
            </div>
        </AppLayout>
    );
}
