import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem } from '@/types';
import { Head, Link } from '@inertiajs/react';
import { Edit, Plus, Trash2, Eye, Shield, Users, Key } from 'lucide-react';
import { useCrudOperations } from '@/hooks/use-crud-operations';
import { ServerDataTable, PaginatedData } from '@/components/ui/server-data-table';
import { ColumnDef } from '@tanstack/react-table';
import { ArrowUpDown } from 'lucide-react';

interface Permission {
    id: number;
    name: string;
}

interface Role {
    id: number;
    name: string;
    guard_name: string;
    description?: string;
    permissions?: Permission[];
    users_count?: number;
    created_at: string;
    updated_at: string;
}

interface Props {
    roles: PaginatedData<Role>;
    filters: {
        search?: string;
    };
}

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Dashboard', href: '/dashboard' },
    { title: 'Roles', href: '/roles' },
];

export default function RolesIndex({ roles, filters }: Props) {
    const { handleDelete } = useCrudOperations({
        entityName: 'Rol',
        entityNamePlural: 'Roles',
        basePath: '/roles'
    });

    const columns: ColumnDef<Role>[] = [
        {
            accessorKey: "id",
            header: ({ column }) => {
                return (
                    <Button
                        variant="ghost"
                        onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
                        className="h-auto p-0 font-medium"
                    >
                        ID
                        <ArrowUpDown className="ml-2 h-4 w-4" />
                    </Button>
                )
            },
            cell: ({ row }) => <div className="font-mono text-xs">{row.getValue("id")}</div>,
        },
        {
            accessorKey: "name",
            header: ({ column }) => {
                return (
                    <Button
                        variant="ghost"
                        onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
                        className="h-auto p-0 font-medium"
                    >
                        Nombre
                        <ArrowUpDown className="ml-2 h-4 w-4" />
                    </Button>
                )
            },
            cell: ({ row }) => {
                const role = row.original;
                return (
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-emerald-100 dark:bg-emerald-900/20 rounded-lg flex-shrink-0">
                            <Shield className="w-4 h-4 text-emerald-600 dark:text-emerald-400" />
                        </div>
                        <div>
                            <div className="font-medium">{role.name}</div>
                            <div className="text-sm text-muted-foreground">
                                Guard: {role.guard_name}
                            </div>
                        </div>
                    </div>
                );
            },
        },
        {
            accessorKey: "description",
            header: "Descripción",
            cell: ({ row }) => {
                const description = row.getValue("description") as string;
                return (
                    <div className="max-w-md text-sm text-muted-foreground">
                        {description || "Sin descripción"}
                    </div>
                );
            },
        },
        {
            accessorKey: "permissions",
            header: "Permisos",
            cell: ({ row }) => {
                const permissions = row.original.permissions || [];
                return (
                    <div className="flex flex-wrap gap-1 max-w-xs">
                        {permissions.length > 0 ? (
                            <>
                                {permissions.slice(0, 3).map((permission) => (
                                    <Badge key={permission.id} variant="outline" className="text-xs">
                                        {permission.name}
                                    </Badge>
                                ))}
                                {permissions.length > 3 && (
                                    <Badge variant="secondary" className="text-xs">
                                        +{permissions.length - 3} más
                                    </Badge>
                                )}
                            </>
                        ) : (
                            <span className="text-sm text-muted-foreground">Sin permisos</span>
                        )}
                    </div>
                );
            },
        },
        {
            accessorKey: "users_count",
            header: "Usuarios",
            cell: ({ row }) => {
                const usersCount = row.original.users_count || 0;
                return (
                    <div className="flex items-center gap-2">
                        <Users className="w-4 h-4 text-muted-foreground" />
                        <span className="text-sm">{usersCount}</span>
                    </div>
                );
            },
        },
        {
            accessorKey: "created_at",
            header: ({ column }) => {
                return (
                    <Button
                        variant="ghost"
                        onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
                        className="h-auto p-0 font-medium"
                    >
                        Fecha de Creación
                        <ArrowUpDown className="ml-2 h-4 w-4" />
                    </Button>
                )
            },
            cell: ({ row }) => {
                const date = new Date(row.getValue("created_at"));
                return <div className="text-sm">{date.toLocaleDateString('es-ES')}</div>;
            },
        },
        {
            id: "actions",
            header: "Acciones",
            cell: ({ row }) => {
                const role = row.original;

                return (
                    <div className="flex items-center gap-2">
                        <Button variant="ghost" size="sm" asChild>
                            <Link href={`/roles/${role.id}`}>
                                <Eye className="w-4 h-4" />
                            </Link>
                        </Button>
                        <Button variant="ghost" size="sm" asChild>
                            <Link href={`/roles/${role.id}/edit`}>
                                <Edit className="w-4 h-4" />
                            </Link>
                        </Button>
                        <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleDelete(role.id, role.name)}
                            className="hover:bg-red-50 hover:text-red-700 dark:hover:bg-red-900/20"
                        >
                            <Trash2 className="w-4 h-4" />
                        </Button>
                    </div>
                );
            },
        },
    ];

    const renderMobileCard = (role: Role) => (
        <Card className="hover:shadow-md transition-shadow">
            <CardHeader className="pb-3">
                <div className="flex items-start justify-between">
                    <div className="flex items-start gap-3 flex-1">
                        <div className="p-2 bg-emerald-100 dark:bg-emerald-900/20 rounded-lg flex-shrink-0">
                            <Shield className="w-5 h-5 text-emerald-600 dark:text-emerald-400" />
                        </div>
                        <div className="min-w-0 flex-1">
                            <CardTitle className="text-lg">{role.name}</CardTitle>
                            <CardDescription className="mt-1">
                                Guard: {role.guard_name}
                            </CardDescription>
                            {role.description && (
                                <CardDescription className="mt-1">
                                    {role.description}
                                </CardDescription>
                            )}
                        </div>
                    </div>
                </div>
            </CardHeader>
            <CardContent className="pt-0">
                <div className="space-y-3">
                    {/* Permisos */}
                    <div>
                        <p className="text-sm font-medium text-muted-foreground mb-2">Permisos:</p>
                        <div className="flex flex-wrap gap-1">
                            {role.permissions && role.permissions.length > 0 ? (
                                <>
                                    {role.permissions.slice(0, 3).map((permission) => (
                                        <Badge key={permission.id} variant="outline" className="text-xs">
                                            {permission.name}
                                        </Badge>
                                    ))}
                                    {role.permissions.length > 3 && (
                                        <Badge variant="secondary" className="text-xs">
                                            +{role.permissions.length - 3} más
                                        </Badge>
                                    )}
                                </>
                            ) : (
                                <span className="text-sm text-muted-foreground">Sin permisos</span>
                            )}
                        </div>
                    </div>

                    {/* Footer */}
                    <div className="flex items-center justify-between pt-2 border-t">
                        <div className="flex items-center gap-4">
                            <div className="flex items-center gap-1">
                                <Users className="w-4 h-4 text-muted-foreground" />
                                <span className="text-sm">{role.users_count || 0} usuarios</span>
                            </div>
                            <p className="text-xs text-muted-foreground">
                                Creado: {new Date(role.created_at).toLocaleDateString('es-ES')}
                            </p>
                        </div>
                        <div className="flex items-center gap-1">
                            <Button variant="ghost" size="sm" asChild>
                                <Link href={`/roles/${role.id}`}>
                                    <Eye className="w-4 h-4" />
                                </Link>
                            </Button>
                            <Button variant="ghost" size="sm" asChild>
                                <Link href={`/roles/${role.id}/edit`}>
                                    <Edit className="w-4 h-4" />
                                </Link>
                            </Button>
                            <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => handleDelete(role.id, role.name)}
                                className="hover:bg-red-50 hover:text-red-700 dark:hover:bg-red-900/20"
                            >
                                <Trash2 className="w-4 h-4" />
                            </Button>
                        </div>
                    </div>
                </div>
            </CardContent>
        </Card>
    );

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Roles" />

            <div className="flex h-full flex-1 flex-col gap-4 p-4 lg:gap-6 lg:p-6">
                {/* Header */}
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-emerald-100 dark:bg-emerald-900/20 rounded-lg">
                            <Shield className="w-6 h-6 text-emerald-600 dark:text-emerald-400" />
                        </div>
                        <div>
                            <h1 className="text-2xl font-bold text-slate-900 dark:text-white sm:text-3xl">
                                Roles
                            </h1>
                            <p className="text-slate-600 dark:text-slate-400 mt-1 text-sm sm:text-base">
                                Gestiona los roles y sus permisos en el sistema
                            </p>
                        </div>
                    </div>
                    <div className="hidden sm:block">
                        <Button asChild className="bg-emerald-600 hover:bg-emerald-700 w-full sm:w-auto">
                            <Link href="/roles/create">
                                <Plus className="w-4 h-4 mr-2" />
                                Nuevo Rol
                            </Link>
                        </Button>
                    </div>
                </div>
                <div className="block sm:hidden">
                    <Button asChild className="bg-emerald-600 hover:bg-emerald-700 w-full mt-2">
                        <Link href="/roles/create">
                            <Plus className="w-4 h-4 mr-2" />
                            Nuevo Rol
                        </Link>
                    </Button>
                </div>
                {/* DataTable */}
                <ServerDataTable
                    columns={columns}
                    paginatedData={roles}
                    searchKey="name"
                    searchPlaceholder="Buscar roles..."
                    emptyMessage="No se encontraron roles. Crea tu primer rol para comenzar."
                    renderMobileCard={renderMobileCard}
                    routeName="/roles"
                    initialSearch={filters?.search || ''}
                />
            </div>
        </AppLayout>
    );
}