import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { RoleStatusBadge } from '@/components/ui/status-badge';
import { type RoleDetail, type User } from '@/types';
import { Link } from '@inertiajs/react';
import { type ColumnDef } from '@tanstack/react-table';
import { Eye, MoreHorizontal, Pencil, Send, Trash } from 'lucide-react';
import StatusSelector, { StatusOption } from '../status-selector';

// Import or declare the can function used for permissions
declare function can(permission: string): number;

const ACCESS_LEVEL_STYLES: Record<number, string> = {
    1: 'bg-blue-50 text-blue-700 border-blue-200',
    2: 'bg-amber-50 text-amber-700 border-amber-200',
    3: 'bg-purple-50 text-purple-700 border-purple-200',
};

function AccessLevelBadge({ level, label }: { level: number; label: string }) {
    const cls = ACCESS_LEVEL_STYLES[level] ?? ACCESS_LEVEL_STYLES[1];
    return (
        <span className={`inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-medium ${cls}`}>
            {label}
        </span>
    );
}

interface UserTableColumnsParams {
    handleDeleteUser: (userId: number | string) => void;
    handleSendEmail?: (user: User) => void;
    handleEditUser?: (user: User) => void;
    handleUserStatus?: (id: number, status: string) => void;
    statusOptions?: StatusOption[];
    entityLabel?: string;
    userGroup?: string;
    [key: string]: any;
}

export const userTableColumns = (params: UserTableColumnsParams): (ColumnDef<User> & { sorting?: boolean })[] => {
    const { handleDeleteUser, handleSendEmail, handleEditUser, handleUserStatus, statusOptions, entityLabel = 'User', userGroup = 'employee' } = params;

    return [
        {
            accessorKey: 'staff_id',
            header: 'Staff ID',
            sorting: true,
            cell: ({ row }) => {
                const staff_id = row.original.staff_id;
                return (
                    <Link href={route('users.show', row.original.uid)} className="text-blue-600 hover:underline" onClick={(e) => e.stopPropagation()}>
                        {staff_id || ''}
                    </Link>
                );
            },
        },
        {
            accessorKey: 'name',
            header: 'User',
            sorting: true,
            cell: ({ row }) => {
                const user = row.original;
                return (
                    <div className="flex items-center gap-3">
                        <Avatar className="h-10 w-10">
                            <AvatarImage src={user.avatar} />
                            <AvatarFallback>{user.name?.charAt(0)}</AvatarFallback>
                        </Avatar>

                        <Link href={route('users.show', user.uid)} className="leading-tight hover:underline" onClick={(e) => e.stopPropagation()}>
                            <div className="text-sm font-semibold sm:text-[15px]">{user.name}</div>
                            <div className="max-w-[180px] text-xs break-all text-muted-foreground sm:max-w-[240px]">{user.email}</div>
                        </Link>
                    </div>
                );
            },
        },
        {
            accessorKey: 'role',
            header: 'Role & Access',
            cell: ({ row }) => {
                const rolesDetail: RoleDetail[] = (row.original as any).roles_detail ?? [];
                if (rolesDetail.length > 0) {
                    return (
                        <div className="flex flex-col gap-1.5">
                            {rolesDetail.map((r) => (
                                <div key={r.id} className="flex items-center gap-1.5 flex-wrap">
                                    <RoleStatusBadge status={r.name} size="sm" />
                                    <AccessLevelBadge level={r.primary_access_level} label={r.access_level_label} />
                                </div>
                            ))}
                        </div>
                    );
                }
                const roles = Array.isArray(row.original.role) ? row.original.role : [row.original.role];
                return (
                    <div className="flex flex-wrap gap-1">
                        {roles.map((r) => (
                            <RoleStatusBadge key={r} status={r} size="sm" />
                        ))}
                    </div>
                );
            },
        },
        {
            accessorKey: 'phone',
            header: 'Phone',
            cell: ({ row }) => {
                const phone: string | undefined = (row.original as any).phone;
                return <p>{phone && String(phone).trim() !== '' ? phone : '+1 (555) 123-4567'}</p>;
            },
        },

        {
            accessorKey: 'updated_at',
            header: 'Updated',
            sorting: true,
            cell: ({ row }) => {
                const updatedAt = row.original.updated_at;
                return <p>{updatedAt || '22 Feb, 2024'}</p>;
            },
        },

        {
            accessorKey: 'status',
            header: 'Status',
            cell: ({ row }) => {
                const status = (row.original.status || 0) as number;
                return <StatusSelector id={row.original.id} handleStatusUpdate={handleUserStatus} status={status} statusOptions={statusOptions} />;
            },
        },
        {
            header: 'Actions',
            accessorKey: 'actions',
            sorting: false,
            cell: ({ row }) => {
                const roles = Array.isArray(row.original.role) ? row.original.role : [row.original.role];
                return (
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button variant="ghost" size="icon" className="h-8 w-8 p-0">
                                <span className="sr-only">Open menu</span>
                                <MoreHorizontal className="h-4 w-4" />
                            </Button>
                        </DropdownMenuTrigger>

                        <DropdownMenuContent align="end" className="w-48">
                            {can(`view_${userGroup}`) > 0 && (
                                <DropdownMenuItem asChild>
                                    <Link href={route('users.show', row.original.uid)} className="flex items-center">
                                        <Eye className="mr-2 h-4 w-4 text-blue-500" />
                                        View Details
                                    </Link>
                                </DropdownMenuItem>
                            )}
                            {can(`edit_${userGroup}`) > 0 && row.original.can_edit !== false && (
                                <DropdownMenuItem className="flex cursor-pointer items-center" onClick={() => handleEditUser?.(row.original)}>
                                    <Pencil className="mr-2 h-4 w-4 text-success" />
                                    Edit {entityLabel}
                                </DropdownMenuItem>
                            )}
                            {can(`edit_${userGroup}`) > 0 && (
                                <DropdownMenuItem className="flex cursor-pointer items-center" onClick={() => handleSendEmail?.(row.original)}>
                                    <Send className="mr-2 h-4 w-4 text-blue-500" />
                                    Send Email
                                </DropdownMenuItem>
                            )}
                            {row.original.can_delete !== false && (
                                <>
                                    <DropdownMenuSeparator />
                                    {can(`delete_${userGroup}`) > 0 && (
                                        <AlertDialog>
                                            <AlertDialogTrigger asChild>
                                                <DropdownMenuItem
                                                    className="flex items-center text-red-600 focus:bg-red-50 focus:text-red-600"
                                                    onSelect={(e) => e.preventDefault()}
                                                >
                                                    <Trash className="mr-2 h-4 w-4" />
                                                    Delete {entityLabel}
                                                </DropdownMenuItem>
                                            </AlertDialogTrigger>
                                            <AlertDialogContent>
                                                <AlertDialogHeader>
                                                    <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
                                                    <AlertDialogDescription>
                                                        This action cannot be undone. This will permanently delete the {entityLabel.toLowerCase()} "{row.original.name}".
                                                    </AlertDialogDescription>
                                                </AlertDialogHeader>
                                                <AlertDialogFooter>
                                                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                                                    <AlertDialogAction
                                                        onClick={() => handleDeleteUser(row.original.uid)}
                                                        className="bg-red-600 hover:bg-red-700"
                                                    >
                                                        Delete
                                                    </AlertDialogAction>
                                                </AlertDialogFooter>
                                            </AlertDialogContent>
                                        </AlertDialog>
                                    )}
                                </>
                            )}
                        </DropdownMenuContent>
                    </DropdownMenu>
                );
            },
        },
    ];
};
