import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem, SurveyQuestion } 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';

type SurveyOptionInput = {
    option: string;
};

type EditQuestionForm = {
    question: string;
    type: 'single_choice' | 'multiple_choice' | 'text';
    options: SurveyOptionInput[];
};

export default function Edit({ survey, surveyQuestion }: { survey: any, surveyQuestion: SurveyQuestion }) {
    const questionInput = useRef<HTMLInputElement>(null);

    const initialOptions = surveyQuestion.options && surveyQuestion.options.length > 0 
        ? surveyQuestion.options.map(o => ({ option: o.option })) 
        : [{ option: '' }];

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

    const addOption = () => {
        setData('options', [...data.options, { option: '' }]);
    };

    const removeOption = (index: number) => {
        const newOptions = [...data.options];
        newOptions.splice(index, 1);
        setData('options', newOptions);
    };

    const handleOptionChange = (index: number, val: string) => {
        const newOptions = [...data.options];
        newOptions[index].option = val;
        setData('options', newOptions);
    };

    const handleTypeChange = (value: 'single_choice' | 'multiple_choice' | 'text') => {
        setData({
            ...data,
            type: value,
            options: value === 'text' ? [] : data.options.length ? data.options : [{ option: '' }],
        });
    };

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

        put(route('survey.survey_question.update', { survey: survey.id, survey_question: surveyQuestion.id }), {
            preserveScroll: true,
            onSuccess: () => {
                toast.success('Question updated successfully.');
            },
            onError: (errs) => {
                if (errs.question) {
                    questionInput.current?.focus();
                }
            }
        });
    };

    const breadcrumbs: BreadcrumbItem[] = [
        { title: 'Surveys', href: '/survey' },
        { title: 'Survey Questions', href: route('survey.survey_question.index', survey.id) },
        { title: 'Edit', href: route('survey.survey_question.edit', { survey: survey.id, survey_question: surveyQuestion.id }) },
    ];

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Survey Question Edit" />
            <div className="m-5">

                <div className="flex">
                    <Link className={(buttonVariants({ variant: 'default', className: 'mb-2 ml-auto' }))} href={route('survey.survey_question.index', survey.id)}>
                        Survey Questions List
                    </Link>
                </div>

                <Card>
                    <CardHeader>
                        <CardTitle>Edit Survey Question for "{survey.title}"</CardTitle>
                    </CardHeader>
                    <form onSubmit={editQuestion}>
                        <CardContent>
                            <div className="grid w-full items-center gap-4">
                                
                                {/* Question Field */}
                                <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 survey question"
                                        disabled={processing}
                                    />
                                    <InputError message={errors.question} />
                                </div>

                                {/* Type Field */}
                                <div className="flex flex-col space-y-1.5">
                                    <Label htmlFor="type">Question Type</Label>
                                    <select
                                        id="type"
                                        value={data.type}
                                        onChange={(e) => handleTypeChange(e.target.value as 'single_choice' | 'multiple_choice' | 'text')}
                                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground 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>
                                        <option value="text">Text Answer</option>
                                    </select>
                                    <InputError message={errors.type} />
                                </div>

                                {data.type !== 'text' && (
                                    <div className="mt-4 border p-4 rounded-md">
                                        <div className="flex justify-between items-center mb-4">
                                            <h3 className="font-semibold text-lg">Options</h3>
                                            <Button type="button" onClick={addOption} variant="outline" size="sm" disabled={processing}>
                                                Add Option
                                            </Button>
                                        </div>

                                        {/* General options error if the array itself fails validation */}
                                        <InputError message={errors.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">
                                                        <Input
                                                            value={opt.option}
                                                            onChange={(e) => handleOptionChange(index, e.target.value)}
                                                            placeholder={`Option ${index + 1}`}
                                                            disabled={processing}
                                                            className="flex-1"
                                                        />
                                                        <Button 
                                                            type="button" 
                                                            onClick={() => removeOption(index)} 
                                                            variant="destructive" 
                                                            disabled={data.options.length === 1 || processing}
                                                        >
                                                            Remove
                                                        </Button>
                                                    </div>
                                                    {/* Error for specific option field */}
                                                    <InputError message={errors[`options.${index}.option`] as string | undefined} />
                                                </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>
                    </form>
                </Card>
            </div>
        </AppLayout>
    );
}
