import { ActivityLogSidebar } from '@/components/activity-log/ActivityLogSidebar';
import { useModelActivityLog } from '@/components/activity-log/useModelActivityLog';

// Permission helper is globally injected; declare for TS
declare function can(permission: string): number;
import { DataTable } from '@/components/datatable';
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 { Head, Link, router } from '@inertiajs/react';
import { type ColumnDef } from '@tanstack/react-table';
import { Eye, PenBoxIcon, Plus, Trash } from 'lucide-react';
import type { ReactNode } from 'react';
import { useEffect, useState } from 'react';

interface Role {
    id: number;
    uid: string;
    name: string;
    slug: string;
    can_edit: number;
    can_delete: number;
    permissions: string[];
    created_at: string;
    updated_at: string;
    deleted_at?: string;
}

interface RolesIndexProps {
    rolesData?: any; // loosen type for now to integrate activity modal quickly
}

function RolesIndex({ rolesData = { data: [] } }: RolesIndexProps) {
    const [loading, setLoading] = useState(true);
    const activityLogCtl = useModelActivityLog();
    useEffect(() => {
        // Simulate loading for demonstration
        const timer = setTimeout(() => {
            setLoading(false);
        }, 300); // Reduced to 2 seconds for better UX
        return () => clearTimeout(timer);
    }, []);

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

    // Actual data column definitions
    const dataColumns: (ColumnDef<Role> & { enableSorting?: boolean })[] = [
        {
            accessorKey: 'id',
            header: '#ID',
            enableSorting: true,
            cell: ({ row }) => <div>#{row.original?.id}</div>,
        },
        {
            accessorKey: 'name',
            header: 'User Assign',
            enableSorting: true,
            cell: ({ row }) => <p className="text-base capitalize">{row.original.name}</p>,
        },
        {
            accessorKey: 'permissions',
            header: 'Permissions',
            enableSorting: false,
            cell: ({ row }) => {
                const maxVisible = 3;
                const permissions = row.original.permissions;
                const visiblePermissions = permissions.slice(0, maxVisible);
                const remainingCount = permissions.length - visiblePermissions.length;

                return (
                    <div className="flex flex-wrap gap-1">
                        {visiblePermissions.map((permission) => (
                            <Badge key={permission} variant="outline" className="border-blue-300 bg-blue-100 text-blue-700">
                                {permission}
                            </Badge>
                        ))}
                        {remainingCount > 0 && (
                            <Badge variant="outline" className="border-gray-300 bg-gray-100 text-gray-700">
                                +{remainingCount} more
                            </Badge>
                        )}
                    </div>
                );
            },
        },
        // Optional users_count column removed (not available in Role interface)
        {
            header: 'Actions',
            accessorKey: 'actions',
            enableSorting: false,
            cell: ({ row }) => (
                <div className="flex flex-row gap-2">
                    {can('platform_view_role') && (
                        <Button variant="ghost" size="icon" className="size-8 border text-text-primary" asChild>
                            <Link href={route('roles.show', row.original.uid)}>
                                <Eye className="size-4" />
                            </Link>
                        </Button>
                    )}
                    {can('platform_edit_role') && row.original.can_edit > 0 && (
                        <Button variant="ghost" size="icon" className="size-8 border text-brand-800" asChild>
                            <Link href={route('roles.edit', row.original.uid)}>
                                <PenBoxIcon className="size-4" />
                            </Link>
                        </Button>
                    )}

                    {can('platform_delete_role') && row.original.can_delete > 0 && (
                        <AlertDialog>
                            <AlertDialogTrigger asChild>
                                <Button variant="ghost" size="icon" className="size-8 border text-red-500">
                                    <Trash className="size-4" />
                                </Button>
                            </AlertDialogTrigger>
                            <AlertDialogContent>
                                <AlertDialogHeader>
                                    <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
                                    <AlertDialogDescription>
                                        This action cannot be undone. This will permanently delete the role "{row.original.name}".
                                    </AlertDialogDescription>
                                </AlertDialogHeader>
                                <AlertDialogFooter>
                                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                                    <AlertDialogAction onClick={() => handleDeleteRole(row.original.uid)} className="bg-red-600 hover:bg-red-700">
                                        Delete
                                    </AlertDialogAction>
                                </AlertDialogFooter>
                            </AlertDialogContent>
                        </AlertDialog>
                    )}
                </div>
            ),
        },
    ];
    const handleActivitySidebar = () => {
        return activityLogCtl.show({ modelClass: 'Role', title: 'Role Model Activity' });
    };
    if (loading) {
        return (
            <>
                <Head title="Loading Users..." />
                <SkeletonTableWithStateCard
                    showBreadcrumbs={true}
                    showActionButtons={true}
                    showStats={false}
                    showTable={true}
                    tableRows={6}
                    animation="pulse"
                />
            </>
        );
    }
    return (
        <>
            <Head title="Roles" />
            <div className="flex h-full flex-1 flex-col gap-4 overflow-x-auto rounded-xl p-2">
                <div className=" ">
                    <SectionHeader
                        title="Roles"
                        description="Manage roles and permissions to control access within the platform."
                        className="mb-6"
                        actions={
                            <div className="flex gap-2">
                                {can('platform_create_role') > 0 && (
                                    <Button asChild className="" size="sm">
                                        <Link href={route('roles.create')}>
                                            <Plus className="size-4" />
                                            Add New Role
                                        </Link>
                                    </Button>
                                )}
                                {/* {can('platform_role_activity_log') > 0 && (
                                    <Button variant="outline" size="sm" className="mr-0.5" onClick={() => handleActivitySidebar()}>
                                        <Activity className="size-4" />
                                        <span className="ml-1 hidden sm:inline">Activity</span>
                                    </Button>
                                )} */}
                            </div>
                        }
                    />

                    <DataTable
                        columns={dataColumns}
                        data={loading ? (Array.from({ length: 5 }) as any) : rolesData?.data || []}
                        paginatedData={loading ? undefined : rolesData}
                        tableKey="roles-table"
                        loading={loading}
                        handleActivitySidebar={handleActivitySidebar}
                    />
                </div>
                <ActivityLogSidebar
                    open={activityLogCtl.open}
                    onOpenChange={activityLogCtl.setOpen}
                    modelClass={activityLogCtl.modelClass}
                    modelId={activityLogCtl.modelId}
                    title={activityLogCtl.title}
                />
            </div>
        </>
    );
}

RolesIndex.layout = (page: ReactNode) => (
    <AppLayout
        breadcrumbs={[
            { title: 'Home', href: '/' },
            { title: 'Roles', href: '/roles' },
        ]}
        title="Roles"
    >
        {page}
    </AppLayout>
);

export default RolesIndex;
