import type { FormComponentRef } from '@inertiajs/core';
import { Form, Head, router, usePage } from '@inertiajs/react';
import {
    CircleOff,
    EllipsisVertical,
    Eye,
    EyeOff,
    Info,
    KeyRound,
    Pencil,
    Plus,
    LogOut,
    PanelLeftClose,
    PanelLeftOpen,
    Search,
    Trash2,
    UserCheck,
} from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { toast, Toaster } from 'sonner';
import { AppSidebar } from '@/components/AppSidebar';
import { Button } from '@/components/ui/button';
import { useAppSidebar } from '@/hooks/useAppSidebar';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
    Field,
    FieldError,
    FieldGroup,
    FieldLabel,
} from '@/components/ui/field';
import { Input } from '@/components/ui/input';
import {
    EMAIL_MAX,
    EMAIL_REGEX,
    NAME_MAX,
    PASSWORD_LOWER_REGEX,
    PASSWORD_MAX,
    PASSWORD_MIN,
    PASSWORD_NUMBER_REGEX,
    PASSWORD_SPECIAL_REGEX,
    PASSWORD_UPPER_REGEX,
    USER_STATUS_ACTIVE,
    USER_STATUS_INACTIVE,
    USER_STATUSES,
    stripPaginationLabel,
} from '@/lib/constants';
import { route } from '@/lib/route';
import { cn } from '@/lib/utils';

type SubAdmin = {
    id: number;
    first_name: string;
    last_name: string;
    email: string;
    status: (typeof USER_STATUSES)[number];
};

type TeamFilters = {
    search: string;
    status: 'all' | SubAdmin['status'];
};

type PaginatedSubAdmins = {
    data: SubAdmin[];
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    from: number | null;
    to: number | null;
    links: Array<{ url: string | null; label: string; active: boolean }>;
};

function visitTeam(params: { search?: string; status?: string; page?: number }) {
    router.get(
        route('team'),
        {
            ...(params.search ? { search: params.search } : {}),
            ...(params.status && params.status !== 'all' ? { status: params.status } : {}),
            ...(params.page && params.page > 1 ? { page: params.page } : {}),
        },
        { preserveState: true, replace: true, preserveScroll: true },
    );
}

function subAdminClientErrors(
    data: Record<string, unknown>,
    { requirePassword }: { requirePassword: boolean },
): Record<string, string> {
    const errors: Record<string, string> = {};
    const firstName = String(data.first_name ?? '').trim();
    const lastName = String(data.last_name ?? '').trim();
    const email = String(data.email ?? '').trim();

    if (!firstName) {
        errors.first_name = 'The first name field is required.';
    } else if (firstName.length > NAME_MAX) {
        errors.first_name = `The first name field must not be greater than ${NAME_MAX} characters.`;
    }

    if (!lastName) {
        errors.last_name = 'The last name field is required.';
    } else if (lastName.length > NAME_MAX) {
        errors.last_name = `The last name field must not be greater than ${NAME_MAX} characters.`;
    }

    if (!email) {
        errors.email = 'The email field is required.';
    } else if (email.length > EMAIL_MAX) {
        errors.email = `The email field must not be greater than ${EMAIL_MAX} characters.`;
    } else if (!EMAIL_REGEX.test(email)) {
        errors.email = 'The email field must be a valid email address.';
    }

    if (requirePassword) {
        Object.assign(errors, passwordClientErrors(data));
    }

    return errors;
}

function passwordClientErrors(data: Record<string, unknown>): Record<string, string> {
    const errors: Record<string, string> = {};
    const password = String(data.password ?? '');

    if (!password) {
        errors.password = 'The password field is required.';
    } else if (password.length < PASSWORD_MIN) {
        errors.password = `The password field must be at least ${PASSWORD_MIN} characters.`;
    } else if (password.length > PASSWORD_MAX) {
        errors.password = `The password field must not be greater than ${PASSWORD_MAX} characters.`;
    } else if (
        !PASSWORD_UPPER_REGEX.test(password) ||
        !PASSWORD_LOWER_REGEX.test(password) ||
        !PASSWORD_NUMBER_REGEX.test(password) ||
        !PASSWORD_SPECIAL_REGEX.test(password)
    ) {
        errors.password =
            'The password must include uppercase, lowercase, number, and special character.';
    }

    return errors;
}

export default function Team({
    auth,
    canManageTeam,
    subAdmins,
    filters,
}: {
    auth: { user: { first_name: string; last_name: string; email: string } | null };
    canManageTeam: boolean;
    subAdmins: PaginatedSubAdmins;
    filters: TeamFilters;
}) {
    const { flash } = usePage().props as {
        flash?: { success?: string | null; error?: string | null };
    };

    const formRef = useRef<FormComponentRef | null>(null);
    const passwordFormRef = useRef<FormComponentRef | null>(null);
    const [open, setOpen] = useState(false);
    const [editing, setEditing] = useState<SubAdmin | null>(null);
    const [changingPassword, setChangingPassword] = useState<SubAdmin | null>(null);
    const [deleting, setDeleting] = useState<SubAdmin | null>(null);
    const [deletingBusy, setDeletingBusy] = useState(false);
    const [passwordVisible, setPasswordVisible] = useState(false);
    const [changePasswordVisible, setChangePasswordVisible] = useState(false);
    const [search, setSearch] = useState(filters.search);
    const { collapsed: sidebarCollapsed, mobileOpen, toggleSidebar, closeMobile, showOpenIcon } =
        useAppSidebar();

    useEffect(() => {
        setSearch(filters.search);
    }, [filters.search]);

    useEffect(() => {
        if (flash?.success) {
            toast.success(flash.success);
        }
        if (flash?.error) {
            toast.error(flash.error);
        }
    }, [flash?.success, flash?.error]);

    useEffect(() => {
        const trimmed = search.trim();
        if (trimmed === filters.search) {
            return;
        }

        const id = window.setTimeout(() => {
            visitTeam({ search: trimmed, status: filters.status });
        }, 300);

        return () => window.clearTimeout(id);
    }, [search, filters.search, filters.status]);

    const rows = subAdmins.data;
    const hasActiveFilters = filters.search !== '' || filters.status !== 'all';

    return (
        <>
            <Head title="Sub Admin" />
            <Toaster
                position="bottom-right"
                toastOptions={{
                    classNames: {
                        success:
                            '!bg-green-600 !text-white !border-green-700 [&_[data-icon]]:!text-white',
                        error: '!bg-red-600 !text-white !border-red-700 [&_[data-icon]]:!text-white',
                    },
                }}
            />

            <div className="flex h-svh gap-3 overflow-hidden bg-background p-3">
                <AppSidebar
                    auth={auth}
                    collapsed={sidebarCollapsed}
                    mobileOpen={mobileOpen}
                    onMobileClose={closeMobile}
                    active="team"
                />

                <div className="flex min-h-0 min-w-0 flex-1 flex-col gap-3">
                    <header className="flex h-12 shrink-0 items-center justify-between gap-3 rounded-2xl border border-border bg-card px-4 shadow-sm">
                        <div className="flex min-w-0 items-center gap-3">
                            <Button
                                type="button"
                                variant="ghost"
                                size="icon"
                                className="cursor-pointer"
                                aria-label={showOpenIcon ? 'Open sidebar' : 'Close sidebar'}
                                onClick={toggleSidebar}
                            >
                                {showOpenIcon ? (
                                    <PanelLeftOpen className="size-4" aria-hidden />
                                ) : (
                                    <PanelLeftClose className="size-4" aria-hidden />
                                )}
                            </Button>

                            <div className="min-w-0">
                                <div className="truncate text-sm font-semibold">Sub Admin</div>
                            </div>
                        </div>

                        <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className="h-8 cursor-pointer gap-1.5 text-xs"
                            onClick={() => router.post(route('logout'))}
                        >
                            <LogOut className="size-4" aria-hidden />
                            Sign out
                        </Button>
                    </header>

                    <main className="flex min-h-0 flex-1 flex-col gap-4 overflow-hidden rounded-2xl border border-border bg-card px-6 py-4 shadow-sm">
                        <div className="flex shrink-0 flex-wrap items-center justify-between gap-3">
                            <div className="flex flex-wrap items-center gap-3">
                                <div className="relative w-full sm:w-80">
                                    <Search
                                        className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"
                                        aria-hidden
                                    />
                                    <Input
                                        type="search"
                                        value={search}
                                        onChange={(e) => setSearch(e.target.value)}
                                        placeholder="Search…"
                                        aria-label="Search Sub Admins"
                                        className="h-9 border-border/80 bg-muted/40 pr-3 pl-9 shadow-none outline-none focus-visible:border-border/80 focus-visible:ring-0"
                                    />
                                </div>

                                <select
                                    value={filters.status}
                                    onChange={(e) =>
                                        visitTeam({
                                            search: search.trim(),
                                            status: e.target.value,
                                        })
                                    }
                                    aria-label="Filter by status"
                                    className="h-9 rounded-lg border border-border/80 bg-muted/40 px-3 text-sm shadow-none outline-none focus:border-border/80"
                                >
                                    <option value="all">All status</option>
                                    <option value={USER_STATUS_ACTIVE}>Active</option>
                                    <option value={USER_STATUS_INACTIVE}>Inactive</option>
                                </select>
                            </div>

                            {canManageTeam && (
                                <Button
                                    type="button"
                                    className="h-9 cursor-pointer gap-1.5"
                                    onClick={() => {
                                        setEditing(null);
                                        setOpen(true);
                                    }}
                                >
                                    <Plus className="size-4" aria-hidden />
                                    Add Sub Admin
                                </Button>
                            )}
                        </div>

                        {!canManageTeam && (
                            <p className="text-sm text-muted-foreground">
                                Only Super Admin can add Sub Admin users.
                            </p>
                        )}

                        <div className="flex min-h-0 flex-1 flex-col gap-3">
                            <div className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-border bg-background">
                                <div
                                    className={cn(
                                        'grid shrink-0 gap-3 bg-muted/40 px-4 py-2.5 text-sm font-medium',
                                        canManageTeam
                                            ? 'grid-cols-[minmax(0,1.2fr)_minmax(0,1.4fr)_7rem_3.5rem]'
                                            : 'grid-cols-[minmax(0,1.2fr)_minmax(0,1.4fr)_7rem]',
                                    )}
                                >
                                    <div>Name</div>
                                    <div>Email</div>
                                    <div>Status</div>
                                    {canManageTeam && <div>Action</div>}
                                </div>

                                <div className="flex min-h-0 flex-1 flex-col">
                                    {rows.length === 0 ? (
                                        <div className="flex flex-1 items-center justify-center px-4 text-sm text-muted-foreground">
                                            {hasActiveFilters
                                                ? 'No matching Sub Admin.'
                                                : 'No Sub Admin found.'}
                                        </div>
                                    ) : (
                                        rows.map((u) => (
                                            <div
                                                key={u.id}
                                                className={cn(
                                                    'grid items-center gap-3 border-t border-border/50 px-4 text-sm',
                                                    rows.length >= subAdmins.per_page
                                                        ? 'flex-1'
                                                        : 'shrink-0 py-2.5',
                                                    canManageTeam
                                                        ? 'grid-cols-[minmax(0,1.2fr)_minmax(0,1.4fr)_7rem_3.5rem]'
                                                        : 'grid-cols-[minmax(0,1.2fr)_minmax(0,1.4fr)_7rem]',
                                                )}
                                            >
                                                <div className="min-w-0 truncate">
                                                    {u.first_name} {u.last_name}
                                                </div>
                                                <div className="min-w-0 truncate text-muted-foreground">
                                                    {u.email}
                                                </div>
                                                <div className="capitalize">{u.status}</div>
                                                {canManageTeam && (
                                                    <div>
                                                        <DropdownMenu>
                                                            <DropdownMenuTrigger
                                                                render={
                                                                    <Button
                                                                        type="button"
                                                                        variant="ghost"
                                                                        size="icon"
                                                                        className="size-8 cursor-pointer"
                                                                        aria-label="Actions"
                                                                    />
                                                                }
                                                            >
                                                                <EllipsisVertical
                                                                    className="size-4"
                                                                    aria-hidden
                                                                />
                                                            </DropdownMenuTrigger>
                                                            <DropdownMenuContent
                                                                align="end"
                                                                className="min-w-52 p-1.5"
                                                            >
                                                                <DropdownMenuItem
                                                                    className="cursor-pointer gap-2 px-2.5 py-2"
                                                                    onClick={() => {
                                                                        setEditing(u);
                                                                        setOpen(true);
                                                                    }}
                                                                >
                                                                    <Pencil aria-hidden />
                                                                    Edit
                                                                </DropdownMenuItem>
                                                                <DropdownMenuSeparator className="my-1.5" />
                                                                <DropdownMenuItem
                                                                    className="cursor-pointer gap-2 px-2.5 py-2"
                                                                    onClick={() =>
                                                                        setChangingPassword(u)
                                                                    }
                                                                >
                                                                    <KeyRound aria-hidden />
                                                                    Change Password
                                                                </DropdownMenuItem>
                                                                <DropdownMenuSeparator className="my-1.5" />
                                                                <DropdownMenuItem
                                                                    className="cursor-pointer gap-2 px-2.5 py-2"
                                                                    onClick={() => {
                                                                        router.put(
                                                                            route(
                                                                                'team.subadmins.update',
                                                                                u.id,
                                                                            ),
                                                                            {
                                                                                first_name:
                                                                                    u.first_name,
                                                                                last_name:
                                                                                    u.last_name,
                                                                                email: u.email,
                                                                                status:
                                                                                    u.status ===
                                                                                    USER_STATUS_ACTIVE
                                                                                        ? USER_STATUS_INACTIVE
                                                                                        : USER_STATUS_ACTIVE,
                                                                            },
                                                                        );
                                                                    }}
                                                                >
                                                                    {u.status ===
                                                                    USER_STATUS_ACTIVE ? (
                                                                        <>
                                                                            <CircleOff
                                                                                aria-hidden
                                                                            />
                                                                            Set Inactive
                                                                        </>
                                                                    ) : (
                                                                        <>
                                                                            <UserCheck
                                                                                aria-hidden
                                                                            />
                                                                            Set Active
                                                                        </>
                                                                    )}
                                                                </DropdownMenuItem>
                                                                <DropdownMenuSeparator className="my-1.5" />
                                                                <DropdownMenuItem
                                                                    variant="destructive"
                                                                    className="cursor-pointer gap-2 px-2.5 py-2"
                                                                    onClick={() => setDeleting(u)}
                                                                >
                                                                    <Trash2 aria-hidden />
                                                                    Delete
                                                                </DropdownMenuItem>
                                                            </DropdownMenuContent>
                                                        </DropdownMenu>
                                                    </div>
                                                )}
                                            </div>
                                        ))
                                    )}
                                </div>
                            </div>

                            {subAdmins.last_page > 1 && (
                                <div className="flex shrink-0 flex-wrap items-center justify-between gap-3">
                                    <p className="text-sm text-muted-foreground">
                                        Showing {subAdmins.from ?? 0}–{subAdmins.to ?? 0} of{' '}
                                        {subAdmins.total}
                                    </p>
                                    <nav className="flex flex-wrap gap-1" aria-label="Pagination">
                                        {subAdmins.links.map((link, index) => {
                                            const label = stripPaginationLabel(link.label);

                                            if (!link.url) {
                                                return (
                                                    <span
                                                        key={`${label}-${index}`}
                                                        className="inline-flex h-8 min-w-8 items-center justify-center rounded-md px-2 text-sm text-muted-foreground"
                                                    >
                                                        {label}
                                                    </span>
                                                );
                                            }

                                            return (
                                                <Button
                                                    key={`${label}-${index}`}
                                                    type="button"
                                                    variant={link.active ? 'default' : 'outline'}
                                                    size="sm"
                                                    className="h-8 min-w-8 cursor-pointer px-2"
                                                    onClick={() =>
                                                        router.get(link.url!, {}, {
                                                            preserveState: true,
                                                            preserveScroll: true,
                                                        })
                                                    }
                                                >
                                                    {label}
                                                </Button>
                                            );
                                        })}
                                    </nav>
                                </div>
                            )}
                        </div>
                    </main>
                </div>
            </div>

            <Dialog
                open={open}
                onOpenChange={(next) => {
                    setOpen(next);
                    if (!next) {
                        setEditing(null);
                        setPasswordVisible(false);
                    }
                }}
            >
                <DialogContent
                    className="gap-0 overflow-hidden p-0 sm:max-w-lg"
                    showCloseButton
                >
                    <DialogHeader className="-mx-0 rounded-t-xl border-b bg-muted/50 p-4">
                        <DialogTitle className="text-lg font-semibold">
                            {editing ? 'Edit Sub Admin' : 'Add Sub Admin'}
                        </DialogTitle>
                        <DialogDescription>
                            {editing
                                ? 'Update Sub Admin details.'
                                : 'Set a password for first login. They must change it after signing in.'}
                        </DialogDescription>
                    </DialogHeader>

                    <Form
                        key={editing?.id ?? 'create'}
                        ref={formRef}
                        action={
                            editing
                                ? route('team.subadmins.update', editing.id)
                                : route('team.subadmins.store')
                        }
                        method={editing ? 'put' : 'post'}
                        resetOnSuccess={['first_name', 'last_name', 'email', 'password']}
                        noValidate
                        onBefore={() => {
                            const errors = subAdminClientErrors(
                                formRef.current?.getData() ?? {},
                                { requirePassword: !editing },
                            );

                            if (Object.keys(errors).length > 0) {
                                formRef.current?.setError(errors);

                                return false;
                            }

                            formRef.current?.clearErrors();
                        }}
                        onSuccess={() => {
                            setOpen(false);
                            setEditing(null);
                            setPasswordVisible(false);
                        }}
                    >
                        {({ errors, processing, clearErrors }) => (
                            <>
                                <FieldGroup className="gap-5 p-4">
                                    <Field data-invalid={!!errors.first_name || undefined}>
                                        <FieldLabel
                                            htmlFor="first_name"
                                            className="text-xs font-medium uppercase tracking-wider text-muted-foreground"
                                        >
                                            First name{' '}
                                            <span className="text-destructive" aria-hidden>
                                                *
                                            </span>
                                        </FieldLabel>
                                        <Input
                                            id="first_name"
                                            name="first_name"
                                            autoComplete="given-name"
                                            autoFocus
                                            maxLength={NAME_MAX}
                                            placeholder="John"
                                            defaultValue={editing?.first_name ?? ''}
                                            aria-invalid={!!errors.first_name || undefined}
                                            onInput={() => clearErrors('first_name')}
                                            className="h-11 border-border/80 bg-muted/40 shadow-none outline-none transition-colors focus-visible:border-border/80 focus-visible:bg-background focus-visible:ring-0 aria-invalid:ring-0"
                                        />
                                        <FieldError>{errors.first_name}</FieldError>
                                    </Field>

                                    <Field data-invalid={!!errors.last_name || undefined}>
                                        <FieldLabel
                                            htmlFor="last_name"
                                            className="text-xs font-medium uppercase tracking-wider text-muted-foreground"
                                        >
                                            Last name{' '}
                                            <span className="text-destructive" aria-hidden>
                                                *
                                            </span>
                                        </FieldLabel>
                                        <Input
                                            id="last_name"
                                            name="last_name"
                                            autoComplete="family-name"
                                            maxLength={NAME_MAX}
                                            placeholder="Doe"
                                            defaultValue={editing?.last_name ?? ''}
                                            aria-invalid={!!errors.last_name || undefined}
                                            onInput={() => clearErrors('last_name')}
                                            className="h-11 border-border/80 bg-muted/40 shadow-none outline-none transition-colors focus-visible:border-border/80 focus-visible:bg-background focus-visible:ring-0 aria-invalid:ring-0"
                                        />
                                        <FieldError>{errors.last_name}</FieldError>
                                    </Field>

                                    <Field data-invalid={!!errors.email || undefined}>
                                        <FieldLabel
                                            htmlFor="email"
                                            className="text-xs font-medium uppercase tracking-wider text-muted-foreground"
                                        >
                                            Email{' '}
                                            <span className="text-destructive" aria-hidden>
                                                *
                                            </span>
                                        </FieldLabel>
                                        <Input
                                            id="email"
                                            name="email"
                                            type="email"
                                            inputMode="email"
                                            autoComplete="email"
                                            maxLength={EMAIL_MAX}
                                            placeholder="subadmin@example.com"
                                            defaultValue={editing?.email ?? ''}
                                            aria-invalid={!!errors.email || undefined}
                                            onInput={() => clearErrors('email')}
                                            className="h-11 border-border/80 bg-muted/40 shadow-none outline-none transition-colors focus-visible:border-border/80 focus-visible:bg-background focus-visible:ring-0 aria-invalid:ring-0"
                                        />
                                        <FieldError>{errors.email}</FieldError>
                                    </Field>

                                    {!editing && (
                                        <Field data-invalid={!!errors.password || undefined}>
                                            <FieldLabel
                                                htmlFor="password"
                                                className="text-xs font-medium uppercase tracking-wider text-muted-foreground"
                                            >
                                                Password{' '}
                                                <span className="text-destructive" aria-hidden>
                                                    *
                                                </span>
                                            </FieldLabel>
                                            <div className="relative">
                                                <Input
                                                    id="password"
                                                    name="password"
                                                    type={passwordVisible ? 'text' : 'password'}
                                                    autoComplete="new-password"
                                                    maxLength={PASSWORD_MAX}
                                                    placeholder="••••••••"
                                                    aria-invalid={!!errors.password || undefined}
                                                    onInput={() => clearErrors('password')}
                                                    className="h-11 border-border/80 bg-muted/40 pr-11 shadow-none outline-none transition-colors focus-visible:border-border/80 focus-visible:bg-background focus-visible:ring-0 aria-invalid:ring-0"
                                                />
                                                <button
                                                    type="button"
                                                    aria-label={
                                                        passwordVisible
                                                            ? 'Hide password'
                                                            : 'Show password'
                                                    }
                                                    aria-pressed={passwordVisible}
                                                    onClick={() =>
                                                        setPasswordVisible((show) => !show)
                                                    }
                                                    className="absolute top-1/2 right-3.5 -translate-y-1/2 cursor-pointer text-muted-foreground/70 transition-colors hover:text-foreground"
                                                >
                                                    {passwordVisible ? (
                                                        <EyeOff
                                                            aria-hidden
                                                            className="size-4"
                                                        />
                                                    ) : (
                                                        <Eye aria-hidden className="size-4" />
                                                    )}
                                                </button>
                                            </div>
                                            <div
                                                role="note"
                                                className="flex gap-3 rounded-lg border border-amber-300/80 bg-amber-50 px-3.5 py-3 text-sm leading-relaxed text-amber-950"
                                            >
                                                <Info
                                                    aria-hidden
                                                    className="mt-0.5 size-4 shrink-0 text-amber-600"
                                                />
                                                <p>
                                                    Min {PASSWORD_MIN} chars, max{' '}
                                                    {PASSWORD_MAX} chars. Must include
                                                    uppercase, lowercase, number, and special
                                                    character.
                                                </p>
                                            </div>
                                            <FieldError>{errors.password}</FieldError>
                                        </Field>
                                    )}
                                </FieldGroup>

                                <DialogFooter className="mx-0 mb-0">
                                    <Button
                                        type="submit"
                                        disabled={processing}
                                        className="h-11 w-full cursor-pointer sm:w-full"
                                    >
                                        {processing
                                            ? editing
                                                ? 'Saving…'
                                                : 'Creating…'
                                            : editing
                                              ? 'Save Changes'
                                              : 'Create Sub Admin'}
                                    </Button>
                                </DialogFooter>
                            </>
                        )}
                    </Form>
                </DialogContent>
            </Dialog>

            <Dialog
                open={!!changingPassword}
                onOpenChange={(next) => {
                    if (!next) {
                        setChangingPassword(null);
                        setChangePasswordVisible(false);
                    }
                }}
            >
                <DialogContent
                    className="gap-0 overflow-hidden p-0 sm:max-w-lg"
                    showCloseButton
                >
                    <DialogHeader className="-mx-0 rounded-t-xl border-b bg-muted/50 p-4 pr-12">
                        <DialogTitle className="text-lg font-semibold">
                            Change Password
                        </DialogTitle>
                        <DialogDescription>
                            {changingPassword
                                ? `Set a new password for ${changingPassword.first_name} ${changingPassword.last_name}.`
                                : 'Set a new password for this Sub Admin.'}
                        </DialogDescription>
                    </DialogHeader>

                    {changingPassword && (
                        <Form
                            key={`password-${changingPassword.id}`}
                            ref={passwordFormRef}
                            action={route(
                                'team.subadmins.password',
                                changingPassword.id,
                            )}
                            method="put"
                            resetOnSuccess={['password']}
                            noValidate
                            onBefore={() => {
                                const errors = passwordClientErrors(
                                    passwordFormRef.current?.getData() ?? {},
                                );

                                if (Object.keys(errors).length > 0) {
                                    passwordFormRef.current?.setError(errors);

                                    return false;
                                }

                                passwordFormRef.current?.clearErrors();
                            }}
                            onSuccess={() => {
                                setChangingPassword(null);
                                setChangePasswordVisible(false);
                            }}
                        >
                            {({ errors, processing, clearErrors }) => (
                                <>
                                    <FieldGroup className="gap-5 p-4">
                                        <Field data-invalid={!!errors.password || undefined}>
                                            <FieldLabel
                                                htmlFor="change_password"
                                                className="text-xs font-medium uppercase tracking-wider text-muted-foreground"
                                            >
                                                Password{' '}
                                                <span className="text-destructive" aria-hidden>
                                                    *
                                                </span>
                                            </FieldLabel>
                                            <div className="relative">
                                                <Input
                                                    id="change_password"
                                                    name="password"
                                                    type={
                                                        changePasswordVisible
                                                            ? 'text'
                                                            : 'password'
                                                    }
                                                    autoComplete="new-password"
                                                    autoFocus
                                                    maxLength={PASSWORD_MAX}
                                                    placeholder="••••••••"
                                                    aria-invalid={
                                                        !!errors.password || undefined
                                                    }
                                                    onInput={() => clearErrors('password')}
                                                    className="h-11 border-border/80 bg-muted/40 pr-11 shadow-none outline-none transition-colors focus-visible:border-border/80 focus-visible:bg-background focus-visible:ring-0 aria-invalid:ring-0"
                                                />
                                                <button
                                                    type="button"
                                                    aria-label={
                                                        changePasswordVisible
                                                            ? 'Hide password'
                                                            : 'Show password'
                                                    }
                                                    aria-pressed={changePasswordVisible}
                                                    onClick={() =>
                                                        setChangePasswordVisible((show) => !show)
                                                    }
                                                    className="absolute top-1/2 right-3.5 -translate-y-1/2 cursor-pointer text-muted-foreground/70 transition-colors hover:text-foreground"
                                                >
                                                    {changePasswordVisible ? (
                                                        <EyeOff
                                                            aria-hidden
                                                            className="size-4"
                                                        />
                                                    ) : (
                                                        <Eye aria-hidden className="size-4" />
                                                    )}
                                                </button>
                                            </div>
                                            <div
                                                role="note"
                                                className="flex gap-3 rounded-lg border border-amber-300/80 bg-amber-50 px-3.5 py-3 text-sm leading-relaxed text-amber-950"
                                            >
                                                <Info
                                                    aria-hidden
                                                    className="mt-0.5 size-4 shrink-0 text-amber-600"
                                                />
                                                <p>
                                                    Min {PASSWORD_MIN} chars, max{' '}
                                                    {PASSWORD_MAX} chars. Must include
                                                    uppercase, lowercase, number, and special
                                                    character.
                                                </p>
                                            </div>
                                            <FieldError>{errors.password}</FieldError>
                                        </Field>
                                    </FieldGroup>

                                    <DialogFooter className="mx-0 mb-0">
                                        <Button
                                            type="submit"
                                            disabled={processing}
                                            className="h-11 w-full cursor-pointer sm:w-full"
                                        >
                                            {processing
                                                ? 'Updating…'
                                                : 'Update Password'}
                                        </Button>
                                    </DialogFooter>
                                </>
                            )}
                        </Form>
                    )}
                </DialogContent>
            </Dialog>

            <Dialog
                open={!!deleting}
                onOpenChange={(next) => {
                    if (!next && !deletingBusy) {
                        setDeleting(null);
                    }
                }}
            >
                <DialogContent
                    className="gap-0 overflow-hidden p-0 sm:max-w-md"
                    showCloseButton
                >
                    <DialogHeader className="-mx-0 rounded-t-xl border-b bg-muted/50 p-4 pr-12">
                        <DialogTitle className="text-lg font-semibold">
                            Delete Sub Admin
                        </DialogTitle>
                    </DialogHeader>

                    <div className="p-4">
                        <DialogDescription className="text-sm leading-relaxed text-muted-foreground">
                            {deleting
                                ? `Are you sure you want to delete ${deleting.first_name} ${deleting.last_name}? This action cannot be undone.`
                                : 'Are you sure you want to delete this Sub Admin?'}
                        </DialogDescription>
                    </div>

                    <DialogFooter className="mx-0 mb-0 gap-2 sm:justify-end">
                        <Button
                            type="button"
                            variant="outline"
                            className="h-10 cursor-pointer"
                            disabled={deletingBusy}
                            onClick={() => setDeleting(null)}
                        >
                            Cancel
                        </Button>
                        <Button
                            type="button"
                            variant="destructive"
                            className="h-10 cursor-pointer"
                            disabled={deletingBusy || !deleting}
                            onClick={() => {
                                if (!deleting) {
                                    return;
                                }

                                setDeletingBusy(true);
                                router.delete(route('team.subadmins.destroy', deleting.id), {
                                    onFinish: () => {
                                        setDeletingBusy(false);
                                        setDeleting(null);
                                    },
                                });
                            }}
                        >
                            {deletingBusy ? 'Deleting…' : 'Delete'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </>
    );
}
