import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem } from '@/types';
import { Head, Link, useForm } from '@inertiajs/react';
import {
    Card,
    CardContent,
    CardFooter,
    CardHeader,
    CardTitle,
} from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import InputError from '@/components/input-error';
import { Button, buttonVariants } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { FormEventHandler, useRef } from 'react';
import { toast } from 'sonner';
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;
    };
}

interface QuestionOption {
    id: number;
    option: string;
    is_correct: boolean;
}

interface QuestionRuleData {
    id: number;
    attempt_number: number;
    path?: string;
    correct_point: number;
    incorrect_point: number;
    correct_interval_days: number;
    incorrect_interval_days: number;
}

interface QuestionData {
    id: number;
    question: string;
    type: 'single_choice' | 'multiple_choice';
    sub_topic_id: number;
    explanation: string;
    options: QuestionOption[];
    question_rules: QuestionRuleData[];
}

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

type RuleInput = {
    attempt_number: number | string;
    path: string;
    correct_point: number | string;
    incorrect_point: number | string;
    correct_interval_days: number | string;
    incorrect_interval_days: number | string;
};

type EditQuestionForm = {
    question: string;
    type: 'single_choice' | 'multiple_choice';
    sub_topic_id: number | string;
    explanation: string;
    options: OptionInput[];
    rules: RuleInput[];
};

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

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

    const initialOptions: OptionInput[] = question.options && question.options.length === 5
        ? question.options.map(o => ({ option: o.option, is_correct: !!o.is_correct }))
        : Array.from({ length: 5 }, () => ({ option: '', is_correct: false }));

    const initialRules: RuleInput[] = question.question_rules && question.question_rules.length > 0
        ? question.question_rules.map(r => ({
            attempt_number: r.attempt_number,
            path: r.path || '',
            correct_point: r.correct_point,
            incorrect_point: r.incorrect_point,
            correct_interval_days: r.correct_interval_days,
            incorrect_interval_days: r.incorrect_interval_days,
        }))
        : [{ attempt_number: 1, path: '', correct_point: 100, incorrect_point: 30, correct_interval_days: 60, incorrect_interval_days: 14 }];

    const { data, setData, errors, put, processing } = useForm<EditQuestionForm>({
        question: question.question ?? '',
        type: question.type ?? 'single_choice',
        sub_topic_id: question.sub_topic_id ?? '',
        explanation: question.explanation ?? '',
        options: initialOptions,
        rules: initialRules,
    });

    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 addRound = () => {
        // Find current max attempt
        const currentRules = [...data.rules];
        const maxAttempt = Math.max(0, ...currentRules.map(r => Number(r.attempt_number)));
        const newAttempt = maxAttempt + 1;

        // Find rules from the previous attempt to generate branches
        const prevRules = currentRules.filter(r => Number(r.attempt_number) === maxAttempt);

        let newRulesToAdd: RuleInput[] = [];

        if (prevRules.length === 0) {
            // fallback
            newRulesToAdd.push({ attempt_number: newAttempt, path: '', correct_point: '', incorrect_point: '', correct_interval_days: '', incorrect_interval_days: '' });
        } else {
            prevRules.forEach(rule => {
                // If correct branch is not retired (interval > 0)
                if (Number(rule.correct_interval_days) > 0) {
                    newRulesToAdd.push({
                        attempt_number: newAttempt,
                        path: rule.path + 'C',
                        correct_point: '', incorrect_point: '', correct_interval_days: '', incorrect_interval_days: ''
                    });
                }
                // If incorrect branch is not retired (interval > 0)
                if (Number(rule.incorrect_interval_days) > 0) {
                    newRulesToAdd.push({
                        attempt_number: newAttempt,
                        path: rule.path + 'I',
                        correct_point: '', incorrect_point: '', correct_interval_days: '', incorrect_interval_days: ''
                    });
                }
            });
        }

        if (newRulesToAdd.length === 0) {
            alert("No paths left to branch. All endpoints are currently 'Retired' (0 days).");
            return;
        }

        setData('rules', [...currentRules, ...newRulesToAdd]);
    };

    const removeRule = (index: number) => {
        const newRules = [...data.rules];
        newRules.splice(index, 1);
        setData('rules', newRules);
    };

    const handleRuleChange = (index: number, field: keyof RuleInput, val: string) => {
        const newRules = [...data.rules];
        (newRules[index] as any)[field] = val;
        setData('rules', newRules);
    };

    const formatPath = (path: string) => {
        if (!path) return "Round 1 (New Question)";
        return path.split('').map(c => c === 'C' ? '✅ Correct' : '❌ Incorrect').join(' → ');
    };

    const editQuestion: FormEventHandler = (e) => {
        e.preventDefault();
        put(route('question.update', question.id), {
            preserveScroll: true,
            onSuccess: () => {
                toast.success('Question updated successfully.');
            },
            onError: (errs) => {
                if (errs.question) {
                    questionInput.current?.focus();
                }
            }
        });
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Question Edit" />
            <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={editQuestion}>
                    {/* Card 1: Question Details */}
                    <Card className="mb-6">
                        <CardHeader>
                            <CardTitle>Edit Question</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <div className="grid w-full items-center gap-4">
                                {/* Question Name */}
                                <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 md:grid-cols-2 gap-4">
                                    {/* Type */}
                                    <div className="flex flex-col space-y-1.5">
                                        <Label htmlFor="type">Question Type</Label>
                                        <select
                                            id="type"
                                            value={data.type}
                                            onChange={(e) => setData('type', e.target.value as 'single_choice' | 'multiple_choice')}
                                            className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                                            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 htmlFor="sub_topic_id">Sub Topic</Label>
                                        <select
                                            id="sub_topic_id"
                                            value={data.sub_topic_id}
                                            onChange={(e) => setData('sub_topic_id', e.target.value)}
                                            className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                                            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>

                                {/* Explanation */}
                                <div className="flex flex-col space-y-1.5">
                                    <Label htmlFor="explanation">Explanation</Label>
                                    <div className="bg-white rounded-md mt-2 pb-10">
                                        <ReactQuill
                                            theme="snow"
                                            value={data.explanation}
                                            onChange={(content) => setData('explanation', content)}
                                            className="max-h-[300px] h-[200px]"
                                            readOnly={processing}
                                        />
                                    </div>
                                    <InputError message={errors.explanation} />
                                </div>

                                {/* 5 Options */}
                                <div className="mt-4 border p-4 rounded-md">
                                    <h3 className="font-semibold text-lg mb-4">Options (5 required)</h3>
                                    <InputError message={(errors as any).options} />

                                    <div className="space-y-3">
                                        {data.options.map((opt, index) => (
                                            <div key={index} className="flex flex-col space-y-1">
                                                <div className="flex gap-2 items-center">
                                                    <span className="text-sm font-medium w-6 shrink-0">{index + 1}.</span>
                                                    <Input
                                                        value={opt.option}
                                                        onChange={(e) => handleOptionChange(index, 'option', e.target.value)}
                                                        placeholder={`Option ${index + 1}`}
                                                        disabled={processing}
                                                        className="flex-1"
                                                    />
                                                    <label className="flex items-center gap-1.5 cursor-pointer shrink-0">
                                                        <input
                                                            type={data.type === 'single_choice' ? 'radio' : 'checkbox'}
                                                            name="correct_option"
                                                            checked={opt.is_correct}
                                                            onChange={(e) => handleOptionChange(index, 'is_correct', e.target.checked)}
                                                            disabled={processing}
                                                            className="w-4 h-4"
                                                        />
                                                        <span className="text-sm">Correct</span>
                                                    </label>
                                                </div>
                                                <InputError message={(errors as any)[`options.${index}.option`] as string | undefined} />
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    {/* Card 2: Rules (Points & Intervals) */}
                    <Card className="mb-6">
                        <CardHeader>
                            <div className="flex justify-between items-center">
                                <CardTitle>Question Rules (Spaced Repetition Tree)</CardTitle>
                                <Button type="button" onClick={addRound} variant="outline" size="sm" disabled={processing}>
                                    + Add Next Round
                                </Button>
                            </div>
                        </CardHeader>
                        <CardContent>
                            <InputError message={(errors as any).rules} />

                            <div className="space-y-6">
                                {data.rules.map((rule, index) => {
                                    const isCorrectRetired = Number(rule.correct_interval_days) === 0 && rule.correct_interval_days !== '';
                                    const isIncorrectRetired = Number(rule.incorrect_interval_days) === 0 && rule.incorrect_interval_days !== '';

                                    return (
                                        <div key={index} className="border p-4 rounded-md shadow-sm relative">
                                            <div className="flex justify-between items-center mb-3 pb-2 border-b">
                                                <div>
                                                    <h4 className="font-semibold text-lg text-primary">Round {rule.attempt_number}</h4>
                                                    <p className="text-sm text-gray-600 font-medium">{formatPath(rule.path)}</p>
                                                    <InputError message={(errors as any)[`rules.${index}.path`] as string | undefined} />
                                                </div>
                                                {data.rules.length > 1 && (
                                                    <Button
                                                        type="button"
                                                        onClick={() => removeRule(index)}
                                                        variant="destructive"
                                                        size="sm"
                                                        disabled={processing}
                                                    >
                                                        Remove
                                                    </Button>
                                                )}
                                            </div>

                                            {/* Correct Path Configuration */}
                                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
                                                <div className="p-4 bg-green-50 border border-green-200 rounded-md">
                                                    <h5 className="font-medium text-green-800 mb-3 flex items-center">
                                                        ✅ If Answered Correctly
                                                    </h5>
                                                    <div className="space-y-3">
                                                        <div className="flex flex-col space-y-1">
                                                            <Label className="text-green-700">Award Points</Label>
                                                            <Input
                                                                type="number"
                                                                value={rule.correct_point}
                                                                onChange={(e) => handleRuleChange(index, 'correct_point', e.target.value)}
                                                                placeholder="100"
                                                                disabled={processing}
                                                            />
                                                            <InputError message={(errors as any)[`rules.${index}.correct_point`] as string | undefined} />
                                                        </div>
                                                        <div className="flex flex-col space-y-1">
                                                            <Label className="text-green-700">Reschedule Interval (days)</Label>
                                                            <div className="flex items-center gap-2">
                                                                <Input
                                                                    type="number"
                                                                    value={rule.correct_interval_days}
                                                                    onChange={(e) => handleRuleChange(index, 'correct_interval_days', e.target.value)}
                                                                    placeholder="60"
                                                                    disabled={processing}
                                                                    min={0}
                                                                    className="flex-1"
                                                                />
                                                                {isCorrectRetired && (
                                                                    <span className="text-xs bg-red-100 text-red-700 px-2 py-1 rounded font-semibold whitespace-nowrap">
                                                                        🏁 Retired
                                                                    </span>
                                                                )}
                                                            </div>
                                                            <InputError message={(errors as any)[`rules.${index}.correct_interval_days`] as string | undefined} />
                                                            <p className="text-xs text-green-700 mt-1">Set to 0 to retire question.</p>
                                                        </div>
                                                    </div>
                                                </div>

                                                {/* Incorrect Path Configuration */}
                                                <div className="p-4 bg-red-50 border border-red-200 rounded-md">
                                                    <h5 className="font-medium text-red-800 mb-3 flex items-center">
                                                        ❌ If Answered Incorrectly
                                                    </h5>
                                                    <div className="space-y-3">
                                                        <div className="flex flex-col space-y-1">
                                                            <Label className="text-red-700">Award Points</Label>
                                                            <Input
                                                                type="number"
                                                                value={rule.incorrect_point}
                                                                onChange={(e) => handleRuleChange(index, 'incorrect_point', e.target.value)}
                                                                placeholder="30"
                                                                disabled={processing}
                                                            />
                                                            <InputError message={(errors as any)[`rules.${index}.incorrect_point`] as string | undefined} />
                                                        </div>
                                                        <div className="flex flex-col space-y-1">
                                                            <Label className="text-red-700">Reschedule Interval (days)</Label>
                                                            <div className="flex items-center gap-2">
                                                                <Input
                                                                    type="number"
                                                                    value={rule.incorrect_interval_days}
                                                                    onChange={(e) => handleRuleChange(index, 'incorrect_interval_days', e.target.value)}
                                                                    placeholder="14"
                                                                    disabled={processing}
                                                                    min={0}
                                                                    className="flex-1"
                                                                />
                                                                {isIncorrectRetired && (
                                                                    <span className="text-xs bg-red-100 text-red-700 px-2 py-1 rounded font-semibold whitespace-nowrap">
                                                                        🏁 Retired
                                                                    </span>
                                                                )}
                                                            </div>
                                                            <InputError message={(errors as any)[`rules.${index}.incorrect_interval_days`] as string | undefined} />
                                                            <p className="text-xs text-red-700 mt-1">Set to 0 to retire question.</p>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        </CardContent>
                        <CardFooter className="flex justify-between mt-5">
                            <Button type="button" variant="outline" onClick={() => window.history.back()} disabled={processing}>
                                Cancel
                            </Button>
                            <Button type="submit" disabled={processing} className={'ml-auto'}>
                                Update
                            </Button>
                        </CardFooter>
                    </Card>
                </form>
            </div>
        </AppLayout>
    );
}
