import { Head, router, useForm } from '@inertiajs/react';
import {
    BarChart2,
    Briefcase,
    CalendarCheck2,
    CalendarDays,
    Camera,
    CheckCircle2,
    Hash,
    Mail,
    MapPin,
    Package,
    Phone,
    PlusCircle,
    PowerOff,
    ShieldCheck,
    Truck,
    User,
    UserCheck,
    UserCog,
    UserMinus,
    UserPlus,
    Users,
    Wrench,
} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { useRef, useState } from 'react';
import { toast } from 'sonner';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { cn, formatUSPhone } from '@/lib/utils';
import {
    LocationMultiSelect,
    type LocationOption,
} from '@/components/location-multi-select';
import {
    index as adminUsers,
    assignRole,
    syncLocations,
    togglePermission,
    toggleStatus,
    updateProfile,
} from '@/routes/admin/users';

// ─── Types ────────────────────────────────────────────────────────────────────

type UserData = {
    id: number;
    name: string;
    email: string;
    phone: string | null;
    avatar: string | null;
    role: string;
    roles: string[];
    permissions: string[];
    locations: LocationOption[];
    is_active: boolean;
};

type Props = {
    user: UserData;
    allPermissions: string[];
    allRoles: string[];
    allLocations: LocationOption[];
};

// ─── Role metadata ─────────────────────────────────────────────────────────────

type RoleMeta = {
    icon: LucideIcon;
    iconBg: string;
    iconColor: string;
    badgeVariant: 'red' | 'blue' | 'yellow' | 'gray';
    description: string;
    selectedBorder: string;
    selectedBg: string;
};

const ROLE_META: Record<string, RoleMeta> = {
    admin: {
        icon: ShieldCheck,
        iconBg: 'bg-red-100 dark:bg-red-900/30',
        iconColor: 'text-red-600 dark:text-red-400',
        badgeVariant: 'red',
        description: 'Full access to all features and settings',
        selectedBorder: 'border-red-400/70 dark:border-red-500/50',
        selectedBg: 'bg-red-50/50 dark:bg-red-950/20',
    },
    manager: {
        icon: Briefcase,
        iconBg: 'bg-blue-100 dark:bg-blue-900/30',
        iconColor: 'text-blue-600 dark:text-blue-400',
        badgeVariant: 'blue',
        description: 'Manage operations, bookings, and customers',
        selectedBorder: 'border-blue-400/70 dark:border-blue-500/50',
        selectedBg: 'bg-blue-50/50 dark:bg-blue-950/20',
    },
    technician: {
        icon: Wrench,
        iconBg: 'bg-amber-100 dark:bg-amber-900/30',
        iconColor: 'text-amber-600 dark:text-amber-400',
        badgeVariant: 'yellow',
        description: 'View and manage assigned service appointments',
        selectedBorder: 'border-amber-400/70 dark:border-amber-500/50',
        selectedBg: 'bg-amber-50/50 dark:bg-amber-950/20',
    },
    customer: {
        icon: User,
        iconBg: 'bg-muted',
        iconColor: 'text-muted-foreground',
        badgeVariant: 'gray',
        description: 'Access to booking portal and personal account only',
        selectedBorder: 'border-muted-foreground/40',
        selectedBg: 'bg-muted/30',
    },
};

// ─── Permission metadata ───────────────────────────────────────────────────────

type PermMeta = { icon: LucideIcon; description: string; group: string };

const PERMISSION_META: Record<string, PermMeta> = {
    'view appointments':   { icon: CalendarDays,  description: 'See all scheduled service bookings',         group: 'Appointments' },
    'manage appointments': { icon: CalendarCheck2, description: 'Create, reschedule, and cancel bookings',    group: 'Appointments' },
    'assign technicians':  { icon: UserPlus,       description: 'Assign staff members to service jobs',       group: 'Appointments' },
    'manage customers':    { icon: Users,          description: 'View and manage customer accounts',          group: 'Customers' },
    'manage users':        { icon: UserCog,        description: 'Manage staff roles and system permissions',  group: 'System' },
    'manage locations':    { icon: MapPin,         description: 'Configure service locations and zones',      group: 'System' },
    'manage packages':     { icon: Package,        description: 'Edit wash packages and pricing tiers',       group: 'System' },
    'manage addons':       { icon: PlusCircle,     description: 'Configure add-on services and pricing',      group: 'System' },
    'manage fleet':        { icon: Truck,          description: 'Manage commercial fleet accounts',           group: 'System' },
    'view reports':        { icon: BarChart2,      description: 'Access analytics and performance data',      group: 'Analytics' },
};

const GROUP_ORDER = ['Appointments', 'Customers', 'System', 'Analytics'];

// ─── Sub-components ────────────────────────────────────────────────────────────

function RoleCard({
    role,
    isSelected,
    onSelect,
}: {
    role: string;
    isSelected: boolean;
    onSelect: () => void;
}) {
    const meta = ROLE_META[role];
    if (!meta) return null;
    const Icon = meta.icon;
    return (
        <button
            type="button"
            onClick={onSelect}
            className={cn(
                'group relative flex w-full cursor-pointer items-start gap-3 rounded-xl border-2 p-4 text-left transition-all duration-150',
                isSelected
                    ? `${meta.selectedBorder} ${meta.selectedBg}`
                    : 'border-border hover:border-muted-foreground/30 hover:bg-muted/30',
            )}
        >
            <div className={cn('mt-0.5 shrink-0 rounded-lg p-2', meta.iconBg)}>
                <Icon className={cn('size-4', meta.iconColor)} />
            </div>
            <div className="min-w-0 flex-1">
                <div className="flex items-center justify-between gap-2">
                    <Badge variant={meta.badgeVariant} className="capitalize">{role}</Badge>
                    {isSelected && <CheckCircle2 className="size-4 shrink-0 text-primary" />}
                </div>
                <p className="text-muted-foreground mt-1.5 text-xs leading-relaxed">
                    {meta.description}
                </p>
            </div>
        </button>
    );
}

function PermissionRow({
    permission,
    hasPermission,
    onToggle,
}: {
    permission: string;
    hasPermission: boolean;
    onToggle: (checked: boolean) => void;
}) {
    const meta = PERMISSION_META[permission];
    const Icon = meta?.icon ?? Package;
    return (
        <div className="flex items-center gap-4 py-3">
            <div className="bg-muted shrink-0 rounded-md p-1.5">
                <Icon className="text-muted-foreground size-3.5" />
            </div>
            <div className="min-w-0 flex-1">
                <Label htmlFor={`perm-${permission}`} className="cursor-pointer text-sm font-medium capitalize">
                    {permission}
                </Label>
                {meta?.description && (
                    <p className="text-muted-foreground mt-0.5 text-xs">{meta.description}</p>
                )}
            </div>
            <Switch
                id={`perm-${permission}`}
                checked={hasPermission}
                onCheckedChange={onToggle}
                className="shrink-0"
            />
        </div>
    );
}

// ─── Main page ─────────────────────────────────────────────────────────────────

export default function AdminUsersEdit({ user, allPermissions, allRoles, allLocations }: Props) {
    const [currentRole, setCurrentRole] = useState(user.role);
    const [isActive, setIsActive] = useState(user.is_active);
    const [selectedLocationIds, setSelectedLocationIds] = useState<number[]>(
        user.locations.map((l) => l.id),
    );
    const [avatarPreview, setAvatarPreview] = useState<string | null>(user.avatar);
    const [localPermissions, setLocalPermissions] = useState<Set<string>>(
        new Set(user.permissions),
    );
    const fileInputRef = useRef<HTMLInputElement>(null);

    const { data, setData, post, processing, errors, reset } = useForm({
        name: user.name,
        email: user.email,
        phone: user.phone ?? '',
        avatar: null as File | null,
    });

    const initials = user.name
        .split(' ')
        .slice(0, 2)
        .map((n) => n[0]?.toUpperCase() ?? '')
        .join('');

    const currentRoleMeta = ROLE_META[currentRole];

    const groupedPermissions = GROUP_ORDER.reduce<Record<string, string[]>>((acc, group) => {
        const perms = allPermissions.filter(
            (p) => (PERMISSION_META[p]?.group ?? 'Other') === group,
        );
        if (perms.length > 0) acc[group] = perms;
        return acc;
    }, {});

    function handleAvatarChange(e: React.ChangeEvent<HTMLInputElement>) {
        const file = e.target.files?.[0];
        if (!file) return;
        setData('avatar', file);
        setAvatarPreview(URL.createObjectURL(file));
    }

    function handleProfileSave() {
        const id = toast.loading('Saving profile…');
        post(updateProfile.url({ user: user.id }), {
            forceFormData: true,
            preserveScroll: true,
            onSuccess: () => {
                toast.success('Profile updated.', { id });
                reset('avatar');
            },
            onError: () => toast.error('Failed to save profile.', { id }),
        });
    }

    function handleRoleChange(role: string) {
        if (role === currentRole) return;
        const prev = currentRole;
        const meta = ROLE_META[role];
        toast.warning(`Switch to "${role}" role?`, {
            description: meta?.description,
            action: {
                label: 'Confirm',
                onClick: () => {
                    setCurrentRole(role);
                    router.post(assignRole.url(), { user_id: user.id, role }, {
                        preserveScroll: true,
                        onSuccess: () => toast.success(`Role updated to "${role}".`),
                        onError: () => {
                            setCurrentRole(prev);
                            toast.error('Failed to update role.');
                        },
                    });
                },
            },
            cancel: { label: 'Cancel', onClick: () => {} },
            duration: 8000,
        });
    }

    function handleStatusToggle(checked: boolean) {
        const prev = isActive;
        setIsActive(checked);
        const label = checked ? 'Activate this account?' : 'Deactivate this account?';
        const desc = checked
            ? 'The user will regain access to the system.'
            : 'The user will lose access until reactivated.';
        toast[checked ? 'info' : 'warning'](label, {
            description: desc,
            action: {
                label: 'Confirm',
                onClick: () => {
                    router.post(
                        toggleStatus.url({ user: user.id }),
                        { is_active: checked },
                        {
                            preserveScroll: true,
                            onSuccess: () =>
                                toast.success(checked ? 'Account activated.' : 'Account deactivated.'),
                            onError: () => {
                                setIsActive(prev);
                                toast.error('Failed to update status.');
                            },
                        },
                    );
                },
            },
            cancel: {
                label: 'Cancel',
                onClick: () => setIsActive(prev),
            },
            duration: 8000,
        });
    }

    function handleLocationsChange(ids: number[]) {
        const prev = selectedLocationIds;
        setSelectedLocationIds(ids);
        const count = ids.length;
        const label = count === 0
            ? 'Remove all location assignments?'
            : `Assign ${count} location${count === 1 ? '' : 's'}?`;
        toast.info(label, {
            action: {
                label: 'Confirm',
                onClick: () => {
                    router.post(
                        syncLocations.url({ user: user.id }),
                        { location_ids: ids },
                        {
                            preserveScroll: true,
                            onSuccess: () => toast.success('Locations updated.'),
                            onError: () => {
                                setSelectedLocationIds(prev);
                                toast.error('Failed to update locations.');
                            },
                        },
                    );
                },
            },
            cancel: { label: 'Cancel', onClick: () => setSelectedLocationIds(prev) },
            duration: 6000,
        });
    }

    function handlePermissionToggle(permission: string, checked: boolean) {
        setLocalPermissions((prev) => {
            const next = new Set(prev);
            if (checked) next.add(permission); else next.delete(permission);
            return next;
        });

        const type = checked ? 'info' : 'warning';
        const label = checked ? `Grant "${permission}"?` : `Revoke "${permission}"?`;
        const desc = checked
            ? 'This gives the user this permission beyond their role defaults.'
            : 'This removes this permission from the user.';

        toast[type](label, {
            description: desc,
            action: {
                label: 'Confirm',
                onClick: () => {
                    router.post(
                        togglePermission.url(),
                        { user_id: user.id, permission_name: permission, checked },
                        {
                            preserveScroll: true,
                            onSuccess: () =>
                                toast.success(checked ? `Granted "${permission}"` : `Revoked "${permission}"`),
                            onError: () => {
                                setLocalPermissions((prev) => {
                                    const revert = new Set(prev);
                                    if (checked) revert.delete(permission); else revert.add(permission);
                                    return revert;
                                });
                                toast.error('Failed to update permission.');
                            },
                        },
                    );
                },
            },
            cancel: {
                label: 'Cancel',
                onClick: () =>
                    setLocalPermissions((prev) => {
                        const revert = new Set(prev);
                        if (checked) revert.delete(permission); else revert.add(permission);
                        return revert;
                    }),
            },
            duration: 7000,
        });
    }

    return (
        <>
            <Head title={`Edit ${user.name}`} />
            <div className="flex h-full flex-1 flex-col gap-6">

                {/* ── Identity hero ── */}
                <Card className={cn(
                    'border-2 transition-colors duration-300',
                    isActive
                        ? 'border-border'
                        : 'border-amber-300/60 dark:border-amber-700/40',
                )}>
                    <CardContent className="p-6">
                        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 sm:items-center">

                            {/* Left half: avatar + name + role + status dot */}
                            <div className="flex items-center gap-4">
                                <div className="relative shrink-0">
                                    <div className="from-primary/20 to-primary/5 flex size-20 items-center justify-center overflow-hidden rounded-full bg-linear-to-br ring-4 ring-border/60">
                                        {avatarPreview ? (
                                            <img
                                                src={avatarPreview}
                                                alt={user.name}
                                                className="size-full object-cover"
                                            />
                                        ) : (
                                            <span className="text-primary text-2xl font-bold tracking-tight">
                                                {initials}
                                            </span>
                                        )}
                                    </div>
                                    {/* Status dot */}
                                    <span className={cn(
                                        'absolute bottom-0.5 right-0.5 size-4 rounded-full border-2 border-background transition-colors duration-300',
                                        isActive
                                            ? 'bg-emerald-500'
                                            : 'bg-amber-400',
                                    )} />
                                </div>
                                <div className="flex min-w-0 flex-col gap-1.5">
                                    <h2 className="truncate text-xl font-bold tracking-tight">{user.name}</h2>
                                    <div className="flex items-center gap-2">
                                        {currentRoleMeta && (
                                            <Badge variant={currentRoleMeta.badgeVariant} className="capitalize">
                                                {currentRole}
                                            </Badge>
                                        )}
                                        <span className={cn(
                                            'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide',
                                            isActive
                                                ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400'
                                                : 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
                                        )}>
                                            {isActive ? (
                                                <><UserCheck className="size-2.5" /> Active</>
                                            ) : (
                                                <><UserMinus className="size-2.5" /> Inactive</>
                                            )}
                                        </span>
                                    </div>
                                </div>
                            </div>

                            {/* Right half: key-value pairs */}
                            <div className="border-border sm:border-l sm:pl-6">
                                <div className="grid grid-cols-2 gap-x-6 gap-y-4">
                                    <div className="flex flex-col gap-1">
                                        <span className="text-muted-foreground flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wider">
                                            <Hash className="size-3.5" />
                                            User ID
                                        </span>
                                        <span className="font-mono text-sm font-semibold">#{user.id}</span>
                                    </div>
                                    <div className="flex flex-col gap-1">
                                        <span className="text-muted-foreground flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wider">
                                            <Mail className="size-3.5" />
                                            Email
                                        </span>
                                        <span className="truncate text-sm font-medium">{user.email}</span>
                                    </div>
                                    <div className="flex flex-col gap-1">
                                        <span className="text-muted-foreground flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wider">
                                            <MapPin className="size-3.5" />
                                            Location
                                        </span>
                                        <span className="text-sm font-medium">
                                            {selectedLocationIds.length > 0
                                                ? allLocations
                                                    .filter((l) => selectedLocationIds.includes(l.id))
                                                    .map((l) => l.name)
                                                    .join(', ')
                                                : <span className="text-muted-foreground">—</span>
                                            }
                                        </span>
                                    </div>
                                    <div className="flex flex-col gap-1">
                                        <span className="text-muted-foreground flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wider">
                                            <Phone className="size-3.5" />
                                            Phone
                                        </span>
                                        <span className="text-sm font-medium">
                                            {user.phone ?? <span className="text-muted-foreground">—</span>}
                                        </span>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </CardContent>
                </Card>

                {/* ── Main grid ── */}
                <div className="grid gap-6 lg:grid-cols-5">

                    {/* Left column */}
                    <div className="flex flex-col gap-4 lg:col-span-2">

                        {/* Profile details card */}
                        <Card>
                            <CardHeader className="pb-3">
                                <CardTitle className="text-base">Profile Details</CardTitle>
                                <CardDescription>
                                    Update name, contact info, and profile photo.
                                </CardDescription>
                            </CardHeader>
                            <CardContent className="flex flex-col gap-5">

                                {/* Avatar upload */}
                                <div className="flex items-center gap-4">
                                    <div
                                        className="group relative size-14 shrink-0 cursor-pointer overflow-hidden rounded-xl"
                                        onClick={() => fileInputRef.current?.click()}
                                        role="button"
                                        tabIndex={0}
                                        onKeyDown={(e) => e.key === 'Enter' && fileInputRef.current?.click()}
                                    >
                                        {avatarPreview ? (
                                            <img
                                                src={avatarPreview}
                                                alt="Avatar preview"
                                                className="size-full object-cover"
                                            />
                                        ) : (
                                            <div className="bg-muted flex size-full items-center justify-center">
                                                <span className="text-muted-foreground text-base font-semibold">
                                                    {initials}
                                                </span>
                                            </div>
                                        )}
                                        <div className="absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 transition-opacity group-hover:opacity-100">
                                            <Camera className="size-4 text-white" />
                                        </div>
                                    </div>
                                    <div>
                                        <button
                                            type="button"
                                            onClick={() => fileInputRef.current?.click()}
                                            className="text-sm font-medium underline-offset-4 hover:underline"
                                        >
                                            Change photo
                                        </button>
                                        <p className="text-muted-foreground mt-0.5 text-xs">
                                            JPG, PNG or GIF · max 2 MB
                                        </p>
                                    </div>
                                    <input
                                        ref={fileInputRef}
                                        type="file"
                                        accept="image/*"
                                        className="sr-only"
                                        onChange={handleAvatarChange}
                                    />
                                </div>

                                {/* Name */}
                                <div className="space-y-1.5">
                                    <Label htmlFor="profile-name">Full name</Label>
                                    <Input
                                        id="profile-name"
                                        value={data.name}
                                        onChange={(e) => setData('name', e.target.value)}
                                        placeholder="Full name"
                                    />
                                    {errors.name && (
                                        <p className="text-destructive text-xs">{errors.name}</p>
                                    )}
                                </div>

                                {/* Email */}
                                <div className="space-y-1.5">
                                    <Label htmlFor="profile-email">Email address</Label>
                                    <Input
                                        id="profile-email"
                                        type="email"
                                        value={data.email}
                                        onChange={(e) => setData('email', e.target.value)}
                                        placeholder="email@example.com"
                                    />
                                    {errors.email && (
                                        <p className="text-destructive text-xs">{errors.email}</p>
                                    )}
                                </div>

                                {/* Phone */}
                                <div className="space-y-1.5">
                                    <Label htmlFor="profile-phone">Phone number</Label>
                                    <Input
                                        id="profile-phone"
                                        type="tel"
                                        value={data.phone}
                                        onChange={(e) => setData('phone', formatUSPhone(e.target.value))}
                                        placeholder="(555) 000-0000"
                                    />
                                    {errors.phone && (
                                        <p className="text-destructive text-xs">{errors.phone}</p>
                                    )}
                                </div>

                                <Button
                                    className="w-full"
                                    onClick={handleProfileSave}
                                    disabled={processing}
                                >
                                    {processing ? 'Saving…' : 'Save profile'}
                                </Button>
                            </CardContent>
                        </Card>

                        {/* Account Status card */}
                        <Card className={cn(
                            'border-2 transition-colors duration-300',
                            isActive
                                ? 'border-border'
                                : 'border-amber-300/60 dark:border-amber-700/40',
                        )}>
                            <CardHeader className="pb-3">
                                <CardTitle className="text-base">Account Status</CardTitle>
                                <CardDescription>
                                    Control whether this staff member can access the system.
                                </CardDescription>
                            </CardHeader>
                            <CardContent>
                                <div className={cn(
                                    'flex items-center gap-4 rounded-xl border-2 p-4 transition-colors duration-300',
                                    isActive
                                        ? 'border-emerald-200 bg-emerald-50/50 dark:border-emerald-800/40 dark:bg-emerald-950/20'
                                        : 'border-amber-200 bg-amber-50/50 dark:border-amber-800/40 dark:bg-amber-950/20',
                                )}>
                                    <div className={cn(
                                        'shrink-0 rounded-xl p-3 transition-colors duration-300',
                                        isActive
                                            ? 'bg-emerald-100 dark:bg-emerald-900/40'
                                            : 'bg-amber-100 dark:bg-amber-900/40',
                                    )}>
                                        {isActive ? (
                                            <UserCheck className="size-5 text-emerald-600 dark:text-emerald-400" />
                                        ) : (
                                            <PowerOff className="size-5 text-amber-600 dark:text-amber-400" />
                                        )}
                                    </div>
                                    <div className="min-w-0 flex-1">
                                        <p className="text-sm font-semibold">
                                            {isActive ? 'Account Active' : 'Account Inactive'}
                                        </p>
                                        <p className="text-muted-foreground mt-0.5 text-xs leading-relaxed">
                                            {isActive
                                                ? 'This staff member can log in and access the system.'
                                                : 'This staff member cannot log in or access the system.'}
                                        </p>
                                    </div>
                                    <Switch
                                        id="account-status"
                                        checked={isActive}
                                        onCheckedChange={handleStatusToggle}
                                        className="shrink-0"
                                    />
                                </div>
                            </CardContent>
                        </Card>

                        {/* Role selection */}
                        <Card>
                            <CardHeader className="pb-3">
                                <CardTitle className="text-base">Role</CardTitle>
                                <CardDescription>
                                    Select access level. Changes apply immediately.
                                </CardDescription>
                            </CardHeader>
                            <CardContent className="flex flex-col gap-2.5">
                                {allRoles.map((role) => (
                                    <RoleCard
                                        key={role}
                                        role={role}
                                        isSelected={currentRole === role}
                                        onSelect={() => handleRoleChange(role)}
                                    />
                                ))}
                            </CardContent>
                        </Card>

                        {/* Location assignment — technician only */}
                        {currentRole === 'technician' && (
                            <Card>
                                <CardHeader className="pb-3">
                                    <CardTitle className="text-base">Location Assignment</CardTitle>
                                    <CardDescription>
                                        Technician sees all appointments at assigned locations.
                                    </CardDescription>
                                </CardHeader>
                                <CardContent className="flex flex-col gap-3">
                                    <LocationMultiSelect
                                        locations={allLocations}
                                        selectedIds={selectedLocationIds}
                                        onChange={handleLocationsChange}
                                    />
                                    {selectedLocationIds.length === 0 && (
                                        <p className="text-muted-foreground text-xs">
                                            No locations assigned — technician will only see their own jobs.
                                        </p>
                                    )}
                                </CardContent>
                            </Card>
                        )}
                    </div>

                    {/* Right column — Permissions */}
                    <Card className="lg:col-span-3">
                        <CardHeader className="pb-3">
                            <CardTitle className="text-base">Direct Permissions</CardTitle>
                            <CardDescription>
                                Overrides role defaults for this individual user. Each toggle saves instantly.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="flex flex-col gap-6">
                            {Object.entries(groupedPermissions).map(([group, perms]) => (
                                <div key={group}>
                                    <div className="mb-1 flex items-center gap-2">
                                        <span className="text-muted-foreground text-[11px] font-semibold uppercase tracking-widest">
                                            {group}
                                        </span>
                                        <div className="border-border h-px flex-1 border-t" />
                                    </div>
                                    <div className="divide-y">
                                        {perms.map((permission) => (
                                            <PermissionRow
                                                key={permission}
                                                permission={permission}
                                                hasPermission={localPermissions.has(permission)}
                                                onToggle={(checked) =>
                                                    handlePermissionToggle(permission, checked)
                                                }
                                            />
                                        ))}
                                    </div>
                                </div>
                            ))}
                        </CardContent>
                    </Card>
                </div>
            </div>
        </>
    );
}

AdminUsersEdit.layout = {
    breadcrumbs: [
        { title: 'Users', href: adminUsers() },
        { title: 'Edit' },
    ],
};
