import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from '@admin/components/ui/alert-dialog';
import { Avatar, AvatarFallback, AvatarImage } from '@admin/components/ui/avatar';
import { Button } from '@admin/components/ui/button';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@admin/components/ui/dropdown-menu';
import { RoleStatusBadge } from '@admin/components/ui/status-badge';
import { type User } from '@admin/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;

interface UserTableColumnsParams {
    handleDeleteUser: (userId: number | string) => void;
    handleSendEmail?: (user: User) => void;
    handleEditUser?: (user: User) => void;
    handleUserStatus?: (id: number, status: string) => void;
    statusOptions?: StatusOption[]; // New parameter for status options
    [key: string]: any; // Allow for additional parameters
}

export const userTableColumns = (params: UserTableColumnsParams): (ColumnDef<User> & { sorting?: boolean })[] => {
    const { handleDeleteUser, handleSendEmail, handleEditUser, handleUserStatus, statusOptions } = 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',
            cell: ({ row }) => {
                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('platform_view_user') > 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('platform_edit_user') > 0 && (
                                <DropdownMenuItem className="flex cursor-pointer items-center" onClick={() => handleEditUser?.(row.original)}>
                                    <Pencil className="mr-2 h-4 w-4 text-success" />
                                    Edit User
                                </DropdownMenuItem>
                            )}
                            {can('platform_send_email_to_user') > 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>
                            )}
                            {!roles?.includes('super admin') && (
                                <>
                                    <DropdownMenuSeparator />
                                    {can('platform_delete_user') > 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 User
                                                </DropdownMenuItem>
                                            </AlertDialogTrigger>
                                            <AlertDialogContent>
                                                <AlertDialogHeader>
                                                    <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
                                                    <AlertDialogDescription>
                                                        This action cannot be undone. This will permanently delete the user "{row.original.name}".
                                                    </AlertDialogDescription>
                                                </AlertDialogHeader>
                                                <AlertDialogFooter>
                                                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                                                    <AlertDialogAction
                                                        onClick={() => handleDeleteUser(row.original.id)}
                                                        className="bg-red-600 hover:bg-red-700"
                                                    >
                                                        Delete
                                                    </AlertDialogAction>
                                                </AlertDialogFooter>
                                            </AlertDialogContent>
                                        </AlertDialog>
                                    )}
                                </>
                            )}
                        </DropdownMenuContent>
                    </DropdownMenu>
                );
            },
        },
    ];
};
