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';

type SubTopicInput = {
    name: string;
};

type EditTopicForm = {
    topic: string;
    sub_topics: SubTopicInput[];
};

interface TopicData {
    id: number;
    name: string;
    sub_topics: { id: number; name: string }[];
}

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

export default function Edit({ topic }: { topic: TopicData }) {
    const topicInput = useRef<HTMLInputElement>(null);

    const initialSubTopics = topic.sub_topics && topic.sub_topics.length > 0
        ? topic.sub_topics.map(s => ({ name: s.name }))
        : [{ name: '' }];

    const { data, setData, errors, put, processing } = useForm<EditTopicForm>({
        topic: topic.name ?? '',
        sub_topics: initialSubTopics,
    });

    const addSubTopic = () => {
        setData('sub_topics', [...data.sub_topics, { name: '' }]);
    };

    const removeSubTopic = (index: number) => {
        const newSubTopics = [...data.sub_topics];
        newSubTopics.splice(index, 1);
        setData('sub_topics', newSubTopics);
    };

    const handleSubTopicChange = (index: number, val: string) => {
        const newSubTopics = [...data.sub_topics];
        newSubTopics[index].name = val;
        setData('sub_topics', newSubTopics);
    };

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

        put(route('topic.update', topic.id), {
            preserveScroll: true,
            onSuccess: () => {
                toast.success('Topic updated successfully.');
            },
            onError: (errs) => {
                if (errs.topic) {
                    topicInput.current?.focus();
                }
            }
        });
    };

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

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

                <Card>
                    <CardHeader>
                        <CardTitle>Edit Topic</CardTitle>
                    </CardHeader>
                    <form onSubmit={editTopic}>
                        <CardContent>
                            <div className="grid w-full items-center gap-4">
                                
                                {/* Topic Name Field */}
                                <div className="flex flex-col space-y-1.5">
                                    <Label htmlFor="topic">Topic Name</Label>
                                    <Input
                                        id="topic"
                                        ref={topicInput}
                                        value={data.topic}
                                        onChange={(e) => setData('topic', e.target.value)}
                                        placeholder="Enter the topic name"
                                        disabled={processing}
                                    />
                                    <InputError message={errors.topic} />
                                </div>

                                {/* Dynamic Sub Topics */}
                                <div className="mt-4 border p-4 rounded-md">
                                    <div className="flex justify-between items-center mb-4">
                                        <h3 className="font-semibold text-lg">Sub Topics</h3>
                                        <Button type="button" onClick={addSubTopic} variant="outline" size="sm" disabled={processing}>
                                            Add Sub Topic
                                        </Button>
                                    </div>

                                    {/* General sub_topics error */}
                                    <InputError message={errors.sub_topics} />

                                    <div className="space-y-3">
                                        {data.sub_topics.map((sub, index) => (
                                            <div key={index} className="flex flex-col space-y-1">
                                                <div className="flex gap-2 items-center">
                                                    <Input
                                                        value={sub.name}
                                                        onChange={(e) => handleSubTopicChange(index, e.target.value)}
                                                        placeholder={`Sub Topic ${index + 1}`}
                                                        disabled={processing}
                                                        className="flex-1"
                                                    />
                                                    <Button 
                                                        type="button" 
                                                        onClick={() => removeSubTopic(index)} 
                                                        variant="destructive" 
                                                        disabled={data.sub_topics.length === 1 || processing}
                                                    >
                                                        Remove
                                                    </Button>
                                                </div>
                                                {/* Error for specific sub topic field */}
                                                <InputError message={(errors as any)[`sub_topics.${index}.name`] 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>
    );
}
