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

interface Props {
    pages: PaginatedDynamicPages;
}

const columns = [
    { label: 'Page Title', key: 'page_title', sortable: true },
    { label: 'Slug', key: 'page_slug', sortable: true },
    // { label: 'Status', key: 'status', sortable: true },
    { label: 'Actions', key: 'actions' },
];

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

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

    const toggleStatus = (id: number) => {
        router.patch(route('dynamic_page.updateStatus', id), {}, {
            preserveScroll: true,
            onSuccess: () => toast.success('Status updated!'),
            onError: () => toast.error('Failed to update status.'),
        });
    };

    return (
        <AppLayout breadcrumbs={[{ title: 'Dynamic Pages', href: '/dynamic_page' }]}>
            <Head title="Dynamic Pages 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">
                                Dynamic Pages List
                            </h1>
                            {/* <Link className={(buttonVariants({ variant: 'default', className: 'ml-auto' }))} href={route('dynamic_page.create')}>
                                Create Dynamic Page
                            </Link> */}
                        </div>
                    </CardHeader>
                    <CardContent>
                        <Table<DynamicPage>
                            data={pages.data}
                            total={pages.total}
                            currentPage={pages.current_page}
                            rowsPerPage={pages.per_page}
                            columns={columns}
                            searchableKeys={['page_title', 'page_slug']}
                            renderCell={(key, value, row) => {
                                if (key === 'status') {
                                    return (
                                        <button
                                            onClick={() => toggleStatus(row.id)}
                                            className={`px-3 py-1 rounded-full text-sm font-medium ${row.status === 'Active'
                                                    ? 'bg-green-100 text-green-800 hover:bg-green-200'
                                                    : 'bg-red-100 text-red-800 hover:bg-red-200'
                                                } transition-colors`}
                                        >
                                            {row.status}
                                        </button>
                                    );
                                }

                                if (key === 'actions') {
                                    return (
                                        <div className="flex gap-2">
                                            <Link
                                                href={route('dynamic_page.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={() => deletePage(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>
    );
}
