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 { 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 Role {
    id: number;
    uid: string;
    name: string;
    slug: string;
    type: number;
    type_label: string;
    type_badge: string;
    primary_access_level: number;
    access_level_label: string;
    status: number;
    status_label: string;
    can_edit: number;
    can_delete: number;
    permissions: string[];
    users_count: number;
    created_at: string;
    updated_at: string;
    deleted_at?: string;
}

interface RolesIndexProps {
    rolesData?: any;
    roleTypes?: { value: number; label: string; color: string; badgeClass: string }[];
    accessLevels?: { value: number; label: string }[];
}

function RolesIndex({ rolesData = { data: [] }, roleTypes = [], accessLevels = [] }: RolesIndexProps) {
    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('roles.destroy', roleUid));
    };

    const handleDuplicateRole = (roleUid: string) => {
        router.post(route('roles.duplicate', roleUid));
    };

    const typeOptions = roleTypes.map((t) => ({ label: t.label, value: t.value }));
    const accessLevelOptions = accessLevels.map((a) => ({ label: a.label, value: a.value }));

    const filters: FilterConfig[] = [
        {
            type: 'searchable-multiselect',
            label: 'Type',
            name: 'type',
            value: clientData?.queryParams?.type || '',
            options: typeOptions,
        },
        {
            type: 'searchable-multiselect',
            label: 'Access Level',
            name: 'access_level',
            value: clientData?.queryParams?.access_level || '',
            options: accessLevelOptions,
        },
        {
            type: 'searchable-multiselect',
            label: 'Status',
            name: 'status',
            value: clientData?.queryParams?.status || '',
            options: [
                { label: 'Active', value: 1 },
                { label: 'Inactive', value: 0 },
            ],
        },
    ];

    const dataColumns: (ColumnDef<Role> & { enableSorting?: boolean })[] = [
        {
            accessorKey: 'id',
            header: '#ID',
            enableSorting: true,
            cell: ({ row }) => <div>#{row.original?.id}</div>,
        },
        {
            accessorKey: 'name',
            header: 'Role Name',
            enableSorting: true,
            cell: ({ row }) => (
                <div>
                    <p className="text-sm font-medium capitalize">{row.original.name}</p>
                    {row.original.users_count > 0 && (
                        <p className="text-xs text-gray-500">{row.original.users_count} user(s)</p>
                    )}
                </div>
            ),
        },
        {
            accessorKey: 'type_label',
            header: 'Type',
            enableSorting: false,
            cell: ({ row }) => (
                <span className={`inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium ${row.original.type_badge}`}>
                    {row.original.type_label}
                </span>
            ),
        },
        {
            accessorKey: 'access_level_label',
            header: 'Primary Access',
            enableSorting: false,
            cell: ({ row }) => (
                <Badge variant="outline" className="border-slate-300 bg-slate-100 text-slate-700">
                    {row.original.access_level_label || `Level ${row.original.primary_access_level}`}
                </Badge>
            ),
        },
        {
            accessorKey: 'status_label',
            header: 'Status',
            enableSorting: false,
            cell: ({ row }) => {
                const isActive = row.original.status === 1;
                return (
                    <Badge
                        variant="outline"
                        className={isActive
                            ? 'border-green-300 bg-green-100 text-green-700'
                            : 'border-red-300 bg-red-100 text-red-700'}
                    >
                        {row.original.status_label}
                    </Badge>
                );
            },
        },
        {
            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>
                );
            },
        },
        {
            header: 'Actions',
            accessorKey: 'actions',
            enableSorting: false,
            cell: ({ row }) => {
                const role = row.original;
                const isInUse = role.users_count > 0;

                return (
                    <div className="flex flex-row gap-1.5">
                        {can('platform_view_role') > 0 && (
                            <Button variant="ghost" size="icon" className="size-8 border text-text-primary" asChild title="View">
                                <Link href={route('roles.show', role.uid)}>
                                    <Eye className="size-4" />
                                </Link>
                            </Button>
                        )}

                        {can('platform_edit_role') > 0 && role.can_edit > 0 && (
                            <Button variant="ghost" size="icon" className="size-8 border text-brand-800" asChild title="Edit">
                                <Link href={route('roles.edit', role.uid)}>
                                    <PenBoxIcon className="size-4" />
                                </Link>
                            </Button>
                        )}

                        {can('platform_create_role') > 0 && (
                            <Button
                                variant="ghost"
                                size="icon"
                                className="size-8 border text-gray-500 hover:text-gray-700"
                                title="Clone role"
                                onClick={() => handleDuplicateRole(role.uid)}
                            >
                                <Copy className="size-4" />
                            </Button>
                        )}

                        {can('platform_delete_role') > 0 && role.can_delete > 0 && (
                            <AlertDialog>
                                <AlertDialogTrigger asChild>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="size-8 border text-red-500"
                                        title={isInUse ? `In use by ${role.users_count} user(s)` : 'Delete'}
                                        disabled={isInUse}
                                    >
                                        <Trash className="size-4" />
                                    </Button>
                                </AlertDialogTrigger>
                                <AlertDialogContent>
                                    <AlertDialogHeader>
                                        <AlertDialogTitle>Delete role "{role.name}"?</AlertDialogTitle>
                                        <AlertDialogDescription>
                                            This will soft-delete the role. It can be restored later.
                                            {isInUse && (
                                                <span className="mt-2 block rounded-md bg-amber-50 px-3 py-2 text-amber-800">
                                                    This role is assigned to {role.users_count} user(s). Remove users from this role before deleting.
                                                </span>
                                            )}
                                        </AlertDialogDescription>
                                    </AlertDialogHeader>
                                    <AlertDialogFooter>
                                        <AlertDialogCancel>Cancel</AlertDialogCancel>
                                        <AlertDialogAction
                                            onClick={() => handleDeleteRole(role.uid)}
                                            className="bg-red-600 hover:bg-red-700"
                                            disabled={isInUse}
                                        >
                                            Delete
                                        </AlertDialogAction>
                                    </AlertDialogFooter>
                                </AlertDialogContent>
                            </AlertDialog>
                        )}
                    </div>
                );
            },
        },
    ];

    const handleActivitySidebar = () => {
        return activityLogCtl.show({ modelClass: 'Role', title: 'Role Model Activity' });
    };

    if (loading) {
        return (
            <>
                <Head title="Loading Roles..." />
                <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>
                    <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 size="sm">
                                        <Link href={route('roles.create')}>
                                            <Plus className="size-4" />
                                            Add New Role
                                        </Link>
                                    </Button>
                                )}
                            </div>
                        }
                    />

                    <DataTable
                        columns={dataColumns}
                        data={loading ? (Array.from({ length: 5 }) as any) : clientData?.data || []}
                        paginatedData={loading ? undefined : clientData}
                        tableKey="roles-table"
                        loading={loading}
                        filters={filters}
                        onNavigate={async (params) => {
                            const url = route('roles.index');
                            const json = await fetchDatatable<Role>(url, params);
                            setClientData({
                                data: json.data,
                                meta: json.meta,
                                queryParams: params,
                                links: {
                                    prev: json.meta.current_page > 1 ? '' : null,
                                    next: json.meta.current_page < json.meta.last_page ? '' : null,
                                },
                            });
                        }}
                        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;
