import { Head, useForm } from '@inertiajs/react';
import React, { useState } from 'react';
import { toast } from 'sonner';
import RbacController from '@/actions/App/Http/Controllers/RbacController';
import Heading from '@/components/heading';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';

interface Permission {
    id: number;
    name: string;
    description: string | null;
    parent_id: number | null;
}

interface Role {
    id: number;
    name: string;
    description: string | null;
    permissions: Permission[];
}

interface User {
    id: number;
    name: string;
    email: string;
    roles: Role[];
}

interface RbacProps {
    roles: Role[];
    permissions: Permission[];
    users: User[];
}

export default function Rbac({ roles, permissions, users }: RbacProps) {
    const [activeTab, setActiveTab] = useState<
        'roles' | 'permissions' | 'users'
    >('roles');

    // Dialog control states
    const [isRoleDialogOpen, setIsRoleDialogOpen] = useState(false);
    const [editingRole, setEditingRole] = useState<Role | null>(null);

    const [isPermissionDialogOpen, setIsPermissionDialogOpen] = useState(false);
    const [editingPermission, setEditingPermission] =
        useState<Permission | null>(null);

    const [isUserDialogOpen, setIsUserDialogOpen] = useState(false);
    const [selectedUser, setSelectedUser] = useState<User | null>(null);
    const [isCreateUserDialogOpen, setIsCreateUserDialogOpen] = useState(false);

    // Form Hooks
    const roleForm = useForm({
        name: '',
        description: '',
        permission_ids: [] as number[],
    });

    const permissionForm = useForm({
        name: '',
        description: '',
        parent_id: '' as string | number,
    });

    const userRolesForm = useForm({
        role_ids: [] as number[],
    });

    const createUserForm = useForm({
        name: '',
        email: '',
        password: '',
        role_ids: [] as number[],
    });

    // Permission Tree Helper
    const buildPermissionTree = (
        items: Permission[],
        parentId: number | null = null,
    ): React.ReactNode => {
        const children = items.filter((item) => item.parent_id === parentId);

        if (children.length === 0) {
            return null;
        }

        return (
            <ul className="mt-2 ml-2 space-y-2 border-l border-muted-foreground/20 pl-4">
                {children.map((child) => {
                    const isChecked = roleForm.data.permission_ids.includes(
                        child.id,
                    );

                    return (
                        <li key={child.id} className="space-y-1">
                            <div className="flex items-start space-x-2 rounded-md p-1 transition-colors hover:bg-muted/50">
                                <Checkbox
                                    id={`perm-${child.id}`}
                                    checked={isChecked}
                                    onCheckedChange={(checked) => {
                                        let updated = [
                                            ...roleForm.data.permission_ids,
                                        ];

                                        if (checked) {
                                            updated.push(child.id);
                                        } else {
                                            updated = updated.filter(
                                                (id) => id !== child.id,
                                            );
                                        }

                                        roleForm.setData(
                                            'permission_ids',
                                            updated,
                                        );
                                    }}
                                />
                                <div className="grid gap-0.5 leading-none">
                                    <label
                                        htmlFor={`perm-${child.id}`}
                                        className="cursor-pointer text-sm leading-none font-medium"
                                    >
                                        {child.name}
                                    </label>
                                    {child.description && (
                                        <p className="text-xs text-muted-foreground">
                                            {child.description}
                                        </p>
                                    )}
                                </div>
                            </div>
                            {buildPermissionTree(items, child.id)}
                        </li>
                    );
                })}
            </ul>
        );
    };

    // Flattened List tree view for Permissions Tab
    const renderPermissionsList = (
        items: Permission[],
        parentId: number | null = null,
        depth = 0,
    ): React.ReactNode => {
        const children = items.filter((item) => item.parent_id === parentId);

        if (children.length === 0) {
            return null;
        }

        return (
            <div className="space-y-2">
                {children.map((child) => (
                    <div key={child.id} className="space-y-2">
                        <div
                            className="flex items-center justify-between rounded-lg border bg-card p-3 transition-all duration-200 hover:bg-muted/30"
                            style={{ marginLeft: `${depth * 24}px` }}
                        >
                            <div className="space-y-1">
                                <div className="flex items-center space-x-2">
                                    <span className="text-sm font-semibold">
                                        {child.name}
                                    </span>
                                    {child.parent_id && (
                                        <span className="text-2xs rounded bg-muted px-1.5 py-0.5 text-muted-foreground">
                                            Child of ID: {child.parent_id}
                                        </span>
                                    )}
                                </div>
                                {child.description && (
                                    <p className="text-xs text-muted-foreground">
                                        {child.description}
                                    </p>
                                )}
                            </div>
                            <div className="flex space-x-2">
                                <Button
                                    size="sm"
                                    variant="outline"
                                    onClick={() => handleEditPermission(child)}
                                >
                                    Edit
                                </Button>
                                <Button
                                    size="sm"
                                    variant="destructive"
                                    onClick={() =>
                                        handleDeletePermission(child.id)
                                    }
                                >
                                    Delete
                                </Button>
                            </div>
                        </div>
                        {renderPermissionsList(items, child.id, depth + 1)}
                    </div>
                ))}
            </div>
        );
    };

    // Role Handlers
    const handleCreateRole = () => {
        setEditingRole(null);
        roleForm.reset();
        roleForm.setData({
            name: '',
            description: '',
            permission_ids: [],
        });
        setIsRoleDialogOpen(true);
    };

    const handleEditRole = (role: Role) => {
        setEditingRole(role);
        roleForm.setData({
            name: role.name,
            description: role.description || '',
            permission_ids: role.permissions.map((p) => p.id),
        });
        setIsRoleDialogOpen(true);
    };

    const handleRoleSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        if (editingRole) {
            roleForm.put(RbacController.updateRole.url(editingRole.id), {
                onSuccess: () => {
                    setIsRoleDialogOpen(false);
                    toast.success('Role updated successfully.');
                },
                onError: (errors: any) => {
                    toast.error(
                        errors.name || errors.error || 'Failed to update role.',
                    );
                },
            });
        } else {
            roleForm.post(RbacController.storeRole.url(), {
                onSuccess: () => {
                    setIsRoleDialogOpen(false);
                    toast.success('Role created successfully.');
                },
                onError: (errors: any) => {
                    toast.error(errors.name || 'Failed to create role.');
                },
            });
        }
    };

    const handleDeleteRole = (id: number) => {
        if (confirm('Are you sure you want to delete this role?')) {
            roleForm.delete(RbacController.destroyRole.url(id), {
                onSuccess: () => toast.success('Role deleted successfully.'),
                onError: (errors: any) =>
                    toast.error(errors.error || 'Failed to delete role.'),
            });
        }
    };

    // Permission Handlers
    const handleCreatePermission = () => {
        setEditingPermission(null);
        permissionForm.reset();
        permissionForm.setData({
            name: '',
            description: '',
            parent_id: '',
        });
        setIsPermissionDialogOpen(true);
    };

    const handleEditPermission = (permission: Permission) => {
        setEditingPermission(permission);
        permissionForm.setData({
            name: permission.name,
            description: permission.description || '',
            parent_id: permission.parent_id || '',
        });
        setIsPermissionDialogOpen(true);
    };

    const handlePermissionSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        // Handle empty parent_id
        const submitData = {
            ...permissionForm.data,
            parent_id:
                permissionForm.data.parent_id === ''
                    ? null
                    : permissionForm.data.parent_id,
        };

        permissionForm.transform(() => submitData);

        if (editingPermission) {
            permissionForm.put(
                RbacController.updatePermission.url(editingPermission.id),
                {
                    onSuccess: () => {
                        setIsPermissionDialogOpen(false);
                        toast.success('Permission updated successfully.');
                    },
                    onError: (errors: any) => {
                        toast.error(
                            errors.name ||
                                errors.parent_id ||
                                'Failed to update permission.',
                        );
                    },
                },
            );
        } else {
            permissionForm.post(RbacController.storePermission.url(), {
                onSuccess: () => {
                    setIsPermissionDialogOpen(false);
                    toast.success('Permission created successfully.');
                },
                onError: (errors: any) => {
                    toast.error(errors.name || 'Failed to create permission.');
                },
            });
        }
    };

    const handleDeletePermission = (id: number) => {
        if (
            confirm(
                'Are you sure you want to delete this permission? This will also delete all child permissions recursively.',
            )
        ) {
            permissionForm.delete(RbacController.destroyPermission.url(id), {
                onSuccess: () =>
                    toast.success('Permission deleted successfully.'),
                onError: () => toast.error('Failed to delete permission.'),
            });
        }
    };

    // User Roles Handlers
    const handleManageUserRoles = (user: User) => {
        setSelectedUser(user);
        userRolesForm.setData({
            role_ids: user.roles.map((r) => r.id),
        });
        setIsUserDialogOpen(true);
    };

    const handleUserRolesSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        if (!selectedUser) {
            return;
        }

        userRolesForm.put(RbacController.updateUserRoles.url(selectedUser.id), {
            onSuccess: () => {
                setIsUserDialogOpen(false);
                toast.success('User roles updated successfully.');
            },
            onError: (errors: any) => {
                toast.error(errors.error || 'Failed to update user roles.');
            },
        });
    };

    const handleCreateUserSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        createUserForm.post(RbacController.storeUser.url(), {
            onSuccess: () => {
                setIsCreateUserDialogOpen(false);
                createUserForm.reset();
                toast.success('User created and roles allocated successfully.');
            },
            onError: (errors: any) => {
                toast.error(
                    errors.email ||
                        errors.password ||
                        errors.name ||
                        'Failed to create user.',
                );
            },
        });
    };

    return (
        <>
            <Head title="Roles & Permissions settings" />
            <div className="space-y-6">
                <Heading
                    title="Roles & Permissions"
                    description="Manage user access, role permissions, and hierarchical permission rules."
                />

                {/* Custom Tab Bar */}
                <div className="flex space-x-1 border-b pb-1">
                    {(['roles', 'permissions', 'users'] as const).map((tab) => (
                        <Button
                            key={tab}
                            variant={activeTab === tab ? 'secondary' : 'ghost'}
                            onClick={() => setActiveTab(tab)}
                            className="capitalize"
                        >
                            {tab}
                        </Button>
                    ))}
                </div>

                {/* Roles Tab Content */}
                {activeTab === 'roles' && (
                    <div className="space-y-4">
                        <div className="flex items-center justify-between">
                            <div>
                                <h2 className="text-lg font-bold">
                                    System Roles
                                </h2>
                                <p className="text-xs text-muted-foreground">
                                    Assign permissions to roles to build a
                                    robust security model.
                                </p>
                            </div>
                            <Button onClick={handleCreateRole}>
                                Create Role
                            </Button>
                        </div>

                        <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                            {roles.map((role) => (
                                <Card
                                    key={role.id}
                                    className="group relative overflow-hidden transition-shadow hover:shadow-md"
                                >
                                    <CardHeader className="pb-3">
                                        <div className="flex items-start justify-between">
                                            <CardTitle className="flex items-center space-x-1.5 text-base font-bold capitalize">
                                                <span>{role.name}</span>
                                                {role.name === 'admin' && (
                                                    <span className="rounded-full bg-primary px-1.5 py-0.5 text-[10px] font-normal text-primary-foreground">
                                                        System Admin
                                                    </span>
                                                )}
                                            </CardTitle>
                                            <div className="flex space-x-1 opacity-80 transition-opacity group-hover:opacity-100">
                                                <Button
                                                    size="sm"
                                                    variant="outline"
                                                    onClick={() =>
                                                        handleEditRole(role)
                                                    }
                                                >
                                                    Edit
                                                </Button>
                                                {role.name !== 'admin' && (
                                                    <Button
                                                        size="sm"
                                                        variant="destructive"
                                                        onClick={() =>
                                                            handleDeleteRole(
                                                                role.id,
                                                            )
                                                        }
                                                    >
                                                        Delete
                                                    </Button>
                                                )}
                                            </div>
                                        </div>
                                        <CardDescription className="text-xs">
                                            {role.description ||
                                                'No description provided.'}
                                        </CardDescription>
                                    </CardHeader>
                                    <CardContent>
                                        <Separator className="mb-3" />
                                        <div className="space-y-1">
                                            <span className="text-xs font-semibold text-muted-foreground">
                                                Assigned Permissions:
                                            </span>
                                            <div className="mt-1 flex flex-wrap gap-1">
                                                {role.permissions.length ===
                                                0 ? (
                                                    <span className="text-xs text-muted-foreground italic">
                                                        No direct permissions.
                                                    </span>
                                                ) : (
                                                    role.permissions.map(
                                                        (p) => (
                                                            <span
                                                                key={p.id}
                                                                className="rounded bg-secondary px-2 py-0.5 text-[10px] text-secondary-foreground"
                                                            >
                                                                {p.name}
                                                            </span>
                                                        ),
                                                    )
                                                )}
                                            </div>
                                        </div>
                                    </CardContent>
                                </Card>
                            ))}
                        </div>
                    </div>
                )}

                {/* Permissions Tab Content */}
                {activeTab === 'permissions' && (
                    <div className="space-y-4">
                        <div className="flex items-center justify-between">
                            <div>
                                <h2 className="text-lg font-bold">
                                    Hierarchical Permissions
                                </h2>
                                <p className="text-xs text-muted-foreground">
                                    Permissions support parent-child nesting.
                                    Assigning a parent permission automatically
                                    grants all of its children.
                                </p>
                            </div>
                            <Button onClick={handleCreatePermission}>
                                Create Permission
                            </Button>
                        </div>

                        <div className="space-y-4 rounded-xl border bg-muted/10 p-4">
                            {permissions.length === 0 ? (
                                <div className="py-6 text-center text-sm text-muted-foreground italic">
                                    No permissions created yet.
                                </div>
                            ) : (
                                // Render root permissions first
                                renderPermissionsList(permissions, null)
                            )}
                        </div>
                    </div>
                )}

                {/* Users Tab Content */}
                {activeTab === 'users' && (
                    <div className="space-y-4">
                        <div className="flex items-center justify-between">
                            <div>
                                <h2 className="text-lg font-bold">
                                    User Roles Management
                                </h2>
                                <p className="text-xs text-muted-foreground">
                                    Modify the roles assigned to individual
                                    users or create new ones.
                                </p>
                            </div>
                            <Button
                                onClick={() => setIsCreateUserDialogOpen(true)}
                            >
                                Create User
                            </Button>
                        </div>

                        <div className="divide-y overflow-hidden rounded-xl border bg-card">
                            {users.map((user) => (
                                <div
                                    key={user.id}
                                    className="flex items-center justify-between p-4 transition-colors hover:bg-muted/10"
                                >
                                    <div className="space-y-1">
                                        <p className="text-sm font-semibold">
                                            {user.name}
                                        </p>
                                        <p className="text-xs text-muted-foreground">
                                            {user.email}
                                        </p>
                                    </div>
                                    <div className="flex items-center space-x-4">
                                        <div className="flex max-w-xs flex-wrap justify-end gap-1">
                                            {user.roles.length === 0 ? (
                                                <span className="text-xs text-muted-foreground italic">
                                                    No roles
                                                </span>
                                            ) : (
                                                user.roles.map((r) => (
                                                    <span
                                                        key={r.id}
                                                        className="rounded bg-secondary px-2 py-0.5 text-xs text-secondary-foreground capitalize"
                                                    >
                                                        {r.name}
                                                    </span>
                                                ))
                                            )}
                                        </div>
                                        <Button
                                            size="sm"
                                            variant="outline"
                                            onClick={() =>
                                                handleManageUserRoles(user)
                                            }
                                        >
                                            Manage Roles
                                        </Button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {/* Role Creation/Editing Dialog */}
                <Dialog
                    open={isRoleDialogOpen}
                    onOpenChange={setIsRoleDialogOpen}
                >
                    <DialogContent className="max-h-[85vh] max-w-md overflow-y-auto">
                        <form onSubmit={handleRoleSubmit} className="space-y-4">
                            <DialogHeader>
                                <DialogTitle>
                                    {editingRole ? 'Edit Role' : 'Create Role'}
                                </DialogTitle>
                                <DialogDescription>
                                    {editingRole
                                        ? 'Update this role details and permissions.'
                                        : 'Add a new custom role to the system.'}
                                </DialogDescription>
                            </DialogHeader>

                            <div className="space-y-3">
                                <div className="space-y-1">
                                    <Label htmlFor="role-name">Role Name</Label>
                                    <Input
                                        id="role-name"
                                        placeholder="e.g. billing-manager"
                                        value={roleForm.data.name}
                                        onChange={(e) =>
                                            roleForm.setData(
                                                'name',
                                                e.target.value
                                                    .toLowerCase()
                                                    .replace(/\s+/g, '-'),
                                            )
                                        }
                                        disabled={editingRole?.name === 'admin'}
                                        required
                                    />
                                </div>

                                <div className="space-y-1">
                                    <Label htmlFor="role-description">
                                        Description
                                    </Label>
                                    <Input
                                        id="role-description"
                                        placeholder="Brief description of the role's purpose"
                                        value={roleForm.data.description}
                                        onChange={(e) =>
                                            roleForm.setData(
                                                'description',
                                                e.target.value,
                                            )
                                        }
                                    />
                                </div>

                                <div className="space-y-2">
                                    <Label className="text-sm font-semibold">
                                        Assign Permissions
                                    </Label>
                                    <p className="text-[10px] text-muted-foreground">
                                        Select the permissions this role
                                        possesses.
                                    </p>
                                    <div className="max-h-56 space-y-1 overflow-y-auto rounded-md border bg-muted/10 p-3">
                                        {permissions.length === 0 ? (
                                            <p className="text-xs text-muted-foreground italic">
                                                No permissions defined.
                                            </p>
                                        ) : (
                                            // Render root permissions first
                                            permissions
                                                .filter(
                                                    (p) => p.parent_id === null,
                                                )
                                                .map((rootPerm) => {
                                                    const isChecked =
                                                        roleForm.data.permission_ids.includes(
                                                            rootPerm.id,
                                                        );

                                                    return (
                                                        <div
                                                            key={rootPerm.id}
                                                            className="space-y-1"
                                                        >
                                                            <div className="flex items-start space-x-2 rounded p-1 transition-colors hover:bg-muted/50">
                                                                <Checkbox
                                                                    id={`perm-${rootPerm.id}`}
                                                                    checked={
                                                                        isChecked
                                                                    }
                                                                    onCheckedChange={(
                                                                        checked,
                                                                    ) => {
                                                                        let updated =
                                                                            [
                                                                                ...roleForm
                                                                                    .data
                                                                                    .permission_ids,
                                                                            ];

                                                                        if (
                                                                            checked
                                                                        ) {
                                                                            updated.push(
                                                                                rootPerm.id,
                                                                            );
                                                                        } else {
                                                                            updated =
                                                                                updated.filter(
                                                                                    (
                                                                                        id,
                                                                                    ) =>
                                                                                        id !==
                                                                                        rootPerm.id,
                                                                                );
                                                                        }

                                                                        roleForm.setData(
                                                                            'permission_ids',
                                                                            updated,
                                                                        );
                                                                    }}
                                                                />
                                                                <div className="grid gap-0.5 leading-none">
                                                                    <label
                                                                        htmlFor={`perm-${rootPerm.id}`}
                                                                        className="cursor-pointer text-sm leading-none font-semibold"
                                                                    >
                                                                        {
                                                                            rootPerm.name
                                                                        }
                                                                    </label>
                                                                    {rootPerm.description && (
                                                                        <p className="text-xs text-muted-foreground">
                                                                            {
                                                                                rootPerm.description
                                                                            }
                                                                        </p>
                                                                    )}
                                                                </div>
                                                            </div>
                                                            {buildPermissionTree(
                                                                permissions,
                                                                rootPerm.id,
                                                            )}
                                                        </div>
                                                    );
                                                })
                                        )}
                                    </div>
                                </div>
                            </div>

                            <DialogFooter className="pt-2">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => setIsRoleDialogOpen(false)}
                                >
                                    Cancel
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={roleForm.processing}
                                >
                                    {editingRole
                                        ? 'Save Changes'
                                        : 'Create Role'}
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>

                {/* Permission Creation/Editing Dialog */}
                <Dialog
                    open={isPermissionDialogOpen}
                    onOpenChange={setIsPermissionDialogOpen}
                >
                    <DialogContent className="max-w-md">
                        <form
                            onSubmit={handlePermissionSubmit}
                            className="space-y-4"
                        >
                            <DialogHeader>
                                <DialogTitle>
                                    {editingPermission
                                        ? 'Edit Permission'
                                        : 'Create Permission'}
                                </DialogTitle>
                                <DialogDescription>
                                    Set name and optionally associate a parent
                                    permission to establish a hierarchy.
                                </DialogDescription>
                            </DialogHeader>

                            <div className="space-y-3">
                                <div className="space-y-1">
                                    <Label htmlFor="perm-name">
                                        Permission Name
                                    </Label>
                                    <Input
                                        id="perm-name"
                                        placeholder="e.g. projects.create"
                                        value={permissionForm.data.name}
                                        onChange={(e) =>
                                            permissionForm.setData(
                                                'name',
                                                e.target.value.toLowerCase(),
                                            )
                                        }
                                        required
                                    />
                                </div>

                                <div className="space-y-1">
                                    <Label htmlFor="perm-desc">
                                        Description
                                    </Label>
                                    <Input
                                        id="perm-desc"
                                        placeholder="Describe what this permission unlocks"
                                        value={permissionForm.data.description}
                                        onChange={(e) =>
                                            permissionForm.setData(
                                                'description',
                                                e.target.value,
                                            )
                                        }
                                    />
                                </div>

                                <div className="space-y-1">
                                    <Label htmlFor="perm-parent">
                                        Parent Permission (Optional)
                                    </Label>
                                    <Select
                                        value={permissionForm.data.parent_id.toString()}
                                        onValueChange={(val) =>
                                            permissionForm.setData(
                                                'parent_id',
                                                val === 'none'
                                                    ? ''
                                                    : Number(val),
                                            )
                                        }
                                    >
                                        <SelectTrigger
                                            id="perm-parent"
                                            className="w-full"
                                        >
                                            <SelectValue placeholder="No Parent (Root Permission)" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="none">
                                                No Parent (Root Permission)
                                            </SelectItem>
                                            {permissions
                                                // Filter out the permission itself to prevent loops
                                                .filter(
                                                    (p) =>
                                                        !editingPermission ||
                                                        p.id !==
                                                            editingPermission.id,
                                                )
                                                .map((p) => (
                                                    <SelectItem
                                                        key={p.id}
                                                        value={p.id.toString()}
                                                    >
                                                        {p.name}
                                                    </SelectItem>
                                                ))}
                                        </SelectContent>
                                    </Select>
                                </div>
                            </div>

                            <DialogFooter className="pt-2">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() =>
                                        setIsPermissionDialogOpen(false)
                                    }
                                >
                                    Cancel
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={permissionForm.processing}
                                >
                                    {editingPermission
                                        ? 'Save Changes'
                                        : 'Create Permission'}
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>

                {/* Manage User Roles Dialog */}
                <Dialog
                    open={isUserDialogOpen}
                    onOpenChange={setIsUserDialogOpen}
                >
                    <DialogContent className="max-w-md">
                        <form
                            onSubmit={handleUserRolesSubmit}
                            className="space-y-4"
                        >
                            <DialogHeader>
                                <DialogTitle>
                                    Manage Roles for {selectedUser?.name}
                                </DialogTitle>
                                <DialogDescription>
                                    Select the security roles to apply to{' '}
                                    {selectedUser?.email}.
                                </DialogDescription>
                            </DialogHeader>

                            <div className="space-y-2">
                                <Label className="text-sm font-semibold">
                                    Roles
                                </Label>
                                <div className="space-y-2 rounded-md border bg-muted/10 p-3">
                                    {roles.map((role) => {
                                        const isChecked =
                                            userRolesForm.data.role_ids.includes(
                                                role.id,
                                            );

                                        return (
                                            <div
                                                key={role.id}
                                                className="flex items-start space-x-2 rounded p-1.5 transition-colors hover:bg-muted/50"
                                            >
                                                <Checkbox
                                                    id={`user-role-${role.id}`}
                                                    checked={isChecked}
                                                    onCheckedChange={(
                                                        checked,
                                                    ) => {
                                                        let updated = [
                                                            ...userRolesForm
                                                                .data.role_ids,
                                                        ];

                                                        if (checked) {
                                                            updated.push(
                                                                role.id,
                                                            );
                                                        } else {
                                                            updated =
                                                                updated.filter(
                                                                    (id) =>
                                                                        id !==
                                                                        role.id,
                                                                );
                                                        }

                                                        userRolesForm.setData(
                                                            'role_ids',
                                                            updated,
                                                        );
                                                    }}
                                                />
                                                <div className="grid gap-0.5 leading-none">
                                                    <label
                                                        htmlFor={`user-role-${role.id}`}
                                                        className="cursor-pointer text-sm leading-none font-medium capitalize"
                                                    >
                                                        {role.name}
                                                    </label>
                                                    {role.description && (
                                                        <p className="text-xs text-muted-foreground">
                                                            {role.description}
                                                        </p>
                                                    )}
                                                </div>
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>

                            <DialogFooter className="pt-2">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => setIsUserDialogOpen(false)}
                                >
                                    Cancel
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={userRolesForm.processing}
                                >
                                    Save Roles
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>

                {/* Create User Dialog */}
                <Dialog
                    open={isCreateUserDialogOpen}
                    onOpenChange={setIsCreateUserDialogOpen}
                >
                    <DialogContent className="max-w-md">
                        <form
                            onSubmit={handleCreateUserSubmit}
                            className="space-y-4"
                        >
                            <DialogHeader>
                                <DialogTitle>Create New User</DialogTitle>
                                <DialogDescription>
                                    Create a user account and assign them
                                    security roles.
                                </DialogDescription>
                            </DialogHeader>

                            <div className="space-y-3">
                                <div className="space-y-1">
                                    <Label htmlFor="create-user-name">
                                        Name
                                    </Label>
                                    <Input
                                        id="create-user-name"
                                        placeholder="Full Name"
                                        value={createUserForm.data.name}
                                        onChange={(e) =>
                                            createUserForm.setData(
                                                'name',
                                                e.target.value,
                                            )
                                        }
                                        required
                                    />
                                </div>

                                <div className="space-y-1">
                                    <Label htmlFor="create-user-email">
                                        Email
                                    </Label>
                                    <Input
                                        id="create-user-email"
                                        type="email"
                                        placeholder="email@example.com"
                                        value={createUserForm.data.email}
                                        onChange={(e) =>
                                            createUserForm.setData(
                                                'email',
                                                e.target.value,
                                            )
                                        }
                                        required
                                    />
                                </div>

                                <div className="space-y-1">
                                    <Label htmlFor="create-user-password">
                                        Password
                                    </Label>
                                    <Input
                                        id="create-user-password"
                                        type="password"
                                        placeholder="Password (min. 8 characters)"
                                        value={createUserForm.data.password}
                                        onChange={(e) =>
                                            createUserForm.setData(
                                                'password',
                                                e.target.value,
                                            )
                                        }
                                        required
                                    />
                                </div>

                                <div className="space-y-2">
                                    <Label className="text-sm font-semibold">
                                        Assign Roles
                                    </Label>
                                    <div className="space-y-2 rounded-md border bg-muted/10 p-3">
                                        {roles.map((role) => {
                                            const isChecked =
                                                createUserForm.data.role_ids.includes(
                                                    role.id,
                                                );

                                            return (
                                                <div
                                                    key={role.id}
                                                    className="flex items-start space-x-2 rounded p-1.5 transition-colors hover:bg-muted/50"
                                                >
                                                    <Checkbox
                                                        id={`create-user-role-${role.id}`}
                                                        checked={isChecked}
                                                        onCheckedChange={(
                                                            checked,
                                                        ) => {
                                                            let updated = [
                                                                ...createUserForm
                                                                    .data
                                                                    .role_ids,
                                                            ];

                                                            if (checked) {
                                                                updated.push(
                                                                    role.id,
                                                                );
                                                            } else {
                                                                updated =
                                                                    updated.filter(
                                                                        (id) =>
                                                                            id !==
                                                                            role.id,
                                                                    );
                                                            }

                                                            createUserForm.setData(
                                                                'role_ids',
                                                                updated,
                                                            );
                                                        }}
                                                    />
                                                    <div className="grid gap-0.5 leading-none">
                                                        <label
                                                            htmlFor={`create-user-role-${role.id}`}
                                                            className="cursor-pointer text-sm leading-none font-medium capitalize"
                                                        >
                                                            {role.name}
                                                        </label>
                                                        {role.description && (
                                                            <p className="text-xs text-muted-foreground">
                                                                {
                                                                    role.description
                                                                }
                                                            </p>
                                                        )}
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>
                                </div>
                            </div>

                            <DialogFooter className="pt-2">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() =>
                                        setIsCreateUserDialogOpen(false)
                                    }
                                >
                                    Cancel
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={createUserForm.processing}
                                >
                                    Create User
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>
            </div>
        </>
    );
}

Rbac.layout = {
    breadcrumbs: [
        {
            title: 'Roles & Permissions',
            href: '/settings/rbac',
        },
    ],
};
