import { ActivityLogSidebar } from '@/components/activity-log/ActivityLogSidebar';
import { useModelActivityLog } from '@/components/activity-log/useModelActivityLog';
import { DataTable } from '@/components/datatable';
import { FilterConfig } from '@/components/datatable-toolbar';
import SectionHeader from '@/components/section-header';
import { SkeletonTableWithStateCard } from '@/components/skeleton';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import AppLayout from '@/layouts/app-layout';
import { fetchDatatable } from '@/lib/datatable-fetch';
import { Head, Link, router } from '@inertiajs/react';
import { type ColumnDef } from '@tanstack/react-table';
import { Copy, Eye, PenBoxIcon, Plus, Trash } from 'lucide-react';
import type { ReactNode } from 'react';
import { useEffect, useState } from 'react';

declare const route: (...args: any[]) => string;

interface AdminRole {
    id: number;
    uid: string;
    name: string;
    slug: string;
    status: string;
    permissions: Array<{ id: number; name: string; slug: string; group_name: string }>;
    created_at: string;
    updated_at: string;
}

interface AdminRolesIndexProps {
    rolesData?: any;
    roleStatuses?: Array<{ label: string; value: string }>;
}

function AdminRolesIndex({ rolesData = { data: [] }, roleStatuses = [] }: AdminRolesIndexProps) {
    const [loading, setLoading] = useState(true);
    const [clientData, setClientData] = useState<any>(rolesData);
    const activityLogCtl = useModelActivityLog();

    useEffect(() => {
        const timer = setTimeout(() => setLoading(false), 300);
        return () => clearTimeout(timer);
    }, []);

    const handleDeleteRole = (roleUid: string) => {
        router.delete(route('admin.roles.destroy', roleUid));
    };

    const handleToggleStatus = (roleUid: string) => {
        router.patch(route('admin.roles.toggle-status', roleUid));
    };

    const statusOptions = roleStatuses.map((s) => ({ label: s.label, value: s.value }));

    const filters: FilterConfig[] = [
        {
            type: 'text',
            label: 'Search',
            name: 'search',
            value: clientData?.queryParams?.search || '',
        },
        {
            type: 'select',
            label: 'Status',
            name: 'status',
            value: clientData?.queryParams?.status || '',
            options: statusOptions,
        },
    ];

    const dataColumns: (ColumnDef<AdminRole> & { enableSorting?: boolean })[] = [
        {
            accessorKey: 'id',
            header: '#ID',
            enableSorting: true,
            cell: ({ row }) => <span className="font-medium">{row.original.id}</span>,
        },
        {
            accessorKey: 'name',
            header: 'Role Name',
            enableSorting: true,
            cell: ({ row }) => (
                <div className="flex flex-col gap-0.5">
                    <span className="font-medium text-primary">{row.original.name}</span>
                    <span className="text-xs text-muted-foreground">@{row.original.slug}</span>
                </div>
            ),
        },
        {
            accessorKey: 'status',
            header: 'Status',
            enableSorting: true,
            cell: ({ row }) => {
                const status = row.original.status;
                const statusLabel = statusOptions.find((s) => s.value === status)?.label || status;
                const statusColorMap: Record<string, string> = {
                    active: 'bg-green-100 text-green-800',
                    inactive: 'bg-gray-100 text-gray-800',
                    deleted: 'bg-red-100 text-red-800',
                };
                return (
                    <Badge className={`${statusColorMap[status] || 'bg-blue-100 text-blue-800'}`}>
                        {statusLabel}
                    </Badge>
                );
            },
        },
        {
            accessorKey: 'permissions',
            header: 'Permissions',
            cell: ({ row }) => (
                <span className="text-sm text-muted-foreground">{row.original.permissions.length} permissions</span>
            ),
        },
        {
            accessorKey: 'created_at',
            header: 'Created',
            enableSorting: true,
            cell: ({ row }) => <span className="text-sm text-muted-foreground">{row.original.created_at}</span>,
        },
        {
            id: 'actions',
            header: 'Actions',
            cell: ({ row }) => (
                <div className="flex gap-2">
                    <Link href={route('admin.roles.show', row.original.uid)}>
                        <Button variant="ghost" size="sm" title="View">
                            <Eye className="h-4 w-4" />
                        </Button>
                    </Link>
                    <Link href={route('admin.roles.edit', row.original.uid)}>
                        <Button variant="ghost" size="sm" title="Edit">
                            <PenBoxIcon className="h-4 w-4" />
                        </Button>
                    </Link>
                    <Button
                        variant="ghost"
                        size="sm"
                        title="Toggle Status"
                        onClick={() => handleToggleStatus(row.original.uid)}
                    >
                        <Copy className="h-4 w-4" />
                    </Button>
                    <AlertDialog>
                        <AlertDialogTrigger asChild>
                            <Button variant="ghost" size="sm" title="Delete">
                                <Trash className="h-4 w-4 text-red-500" />
                            </Button>
                        </AlertDialogTrigger>
                        <AlertDialogContent>
                            <AlertDialogHeader>
                                <AlertDialogTitle>Delete Role</AlertDialogTitle>
                                <AlertDialogDescription>
                                    Are you sure you want to delete this role? This action cannot be undone.
                                </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                                <AlertDialogCancel>Cancel</AlertDialogCancel>
                                <AlertDialogAction onClick={() => handleDeleteRole(row.original.uid)}>
                                    Delete
                                </AlertDialogAction>
                            </AlertDialogFooter>
                        </AlertDialogContent>
                    </AlertDialog>
                </div>
            ),
        },
    ];

    return (
        <>
            <Head title="Admin Roles" />
            <div className="mx-auto flex w-full flex-1 gap-4 p-3 sm:gap-6 sm:p-2">
                {/* Main content */}
                <div className="flex w-full flex-1 flex-col gap-4 sm:gap-6">
                    <SectionHeader
                        title="Admin Roles"
                        description="Manage administrator roles and permissions"
                        actionButton={
                            <Link href={route('admin.roles.create')}>
                                <Button className="gap-2">
                                    <Plus className="h-4 w-4" />
                                    New Role
                                </Button>
                            </Link>
                        }
                    />

                    {loading ? (
                        <SkeletonTableWithStateCard />
                    ) : (
                        <DataTable
                            url={route('admin.roles.index')}
                            columns={dataColumns}
                            data={clientData?.data || []}
                            pagination={clientData}
                            filters={filters}
                            summary={clientData?.roleSummary}
                        />
                    )}
                </div>

                {/* Activity Log Sidebar */}
                <ActivityLogSidebar
                    controller={activityLogCtl}
                    side="right"
                    hideActivityDescription={true}
                    hideTimelineTrail={true}
                />
            </div>
        </>
    );
}

AdminRolesIndex.layout = (page: React.ReactNode) => (
    <AppLayout
        breadcrumbs={[
            { title: 'Dashboard', href: route('dashboard') },
            { title: 'Admin', href: '#' },
            { title: 'Roles', href: route('admin.roles.index') },
        ]}
        title="Admin Roles"
    >
        {page}
    </AppLayout>
);

export default AdminRolesIndex;
