import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem } from '@/types';
import { Head, router, Link } from '@inertiajs/react';
import { toast } from 'sonner';
import Table from '@/components/Table';
import { Edit, Trash } from 'lucide-react';
import { Button, buttonVariants } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardHeader,
} from "@/components/ui/card"

interface TopicRow {
    id: number;
    name: string;
    sub_topics_count: number;
    created_at: string;
    updated_at: string;
    actions?: string;
}

interface PaginatedTopics {
    data: TopicRow[];
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    links: {
        url: string | null;
        label: string;
        active: boolean;
    }[];
}

interface Props {
    topics: PaginatedTopics;
}

const columns = [
    { label: 'Topic Name', key: 'name' as const, sortable: true },
    { label: 'Sub Topics Count', key: 'sub_topics_count' as const },
    { label: 'Actions', key: 'actions' as const },
];

export default function Index({ topics }: Props) {
    const queryParams = new URLSearchParams(window.location.search);
    const search = queryParams.get('search') || '';

    const deleteTopic = (id: number) => {
        if (confirm('Are you sure you want to delete this topic?')) {
            router.delete(route('topic.destroy', { topic: id }), {
                onSuccess: () => toast.success('Topic deleted successfully!'),
                onError: () => toast.error('Failed to delete the topic.'),
            });
        }
    };

    return (
        <AppLayout breadcrumbs={[{ title: 'Topics', href: '/topic' }]}>
            <Head title="Topics List" />

            <div className="m-5">
                <Card>
                    <CardHeader>
                        <div className="flex items-center justify-between">
                            <h1 className="text-2xl font-semibold text-gray-800 dark:text-white">
                                Topics List
                            </h1>
                            <Link className={(buttonVariants({ variant: 'default', className: 'ml-auto' }))} href={route('topic.create')}>
                                Create Topic
                            </Link>
                        </div>
                    </CardHeader>
                    <CardContent>
                        <Table<TopicRow>
                            data={topics.data}
                            total={topics.total}
                            currentPage={topics.current_page}
                            rowsPerPage={topics.per_page}
                            columns={columns}
                            searchableKeys={['name']}
                            renderCell={(key, value, row) => {

                                if (key === 'actions') {
                                    return (
                                        <div className="flex gap-2">
                                            <Link
                                                href={route('topic.edit', row.id)}
                                                className={buttonVariants({ variant: 'secondary', size: 'icon' })}
                                            >
                                                <Edit className="w-4 h-4 text-blue-500" />
                                            </Link>
                                            <button
                                                className={(buttonVariants({ variant: 'secondary', size: 'icon' }))}
                                                onClick={() => deleteTopic(row.id)}
                                            >
                                                <Trash className="w-4 h-4 text-red-500" />
                                            </button>
                                        </div>
                                    );
                                }

                                return value;
                            }}
                            onPageChange={(page) => {
                                const params = Object.fromEntries(new URLSearchParams(window.location.search).entries());
                                router.get(window.location.pathname, {
                                    ...params,
                                    page,
                                }, { preserveState: true, replace: true });
                            }}
                            onPerPageChange={(perPage) => {
                                const params = Object.fromEntries(new URLSearchParams(window.location.search).entries());
                                router.get(window.location.pathname, {
                                    ...params,
                                    page: 1,
                                    per_page: perPage,
                                }, { preserveState: true, replace: true });
                            }}
                            onSearchChange={(searchVal) => {
                                const params = Object.fromEntries(new URLSearchParams(window.location.search).entries());
                                if (searchVal) {
                                    params.search = searchVal;
                                } else {
                                    delete params.search;
                                }
                                router.get(window.location.pathname, {
                                    ...params,
                                    page: 1,
                                }, { preserveState: true, replace: true });
                            }}
                            searchValue={search}
                        />
                    </CardContent>
                </Card>
            </div>
        </AppLayout>
    );
}
