<script setup>
import { computed, reactive, ref } from 'vue';
import { Head, router, useForm, usePage } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import AppCard from '@/Components/ui/AppCard.vue';
import AppTable from '@/Components/ui/AppTable.vue';
import AppModal from '@/Components/ui/AppModal.vue';
import AppTabs from '@/Components/ui/AppTabs.vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import StatusBadge from '@/Components/ui/StatusBadge.vue';

const props = defineProps({
    users: Object,
    filters: Object,
    roles: Array,
    assignableRoles: Array,
    customerTiers: Array,
    statuses: Array,
    apiClientStatuses: {
        type: Array,
        default: () => ['active', 'inactive'],
    },
    banServiceKeys: Array,
    manualAdjustments: Array,
    summary: Object,
});
const page = usePage();

const query = reactive({
    q: props.filters?.q || '',
    role: props.filters?.role || '',
    customer_tier: props.filters?.customer_tier || '',
    status: props.filters?.status || '',
    api_status: props.filters?.api_status || '',
});

const applyFilters = () => {
    router.get(route('admin.users.index'), query, { preserveState: true, replace: true });
};

const showCreateModal = ref(false);
const showAdjustModal = ref(false);
const showEditModal = ref(false);
const showApiModal = ref(false);
const selectedUser = ref(null);

const createUserForm = useForm({
    name: '',
    email: '',
    phone: '',
    password: '',
    password_confirmation: '',
    transaction_pin: '',
    transaction_pin_confirmation: '',
    role: props.assignableRoles?.includes('customer') ? 'customer' : (props.assignableRoles?.[0] || ''),
    customer_tier: props.customerTiers?.includes('subscriber') ? 'subscriber' : (props.customerTiers?.[0] || ''),
    status: 'active',
});

const adjustForm = useForm({
    user_id: '',
    entry_type: 'credit',
    amount: '',
    narration: '',
    reference: '',
});

const editUserForm = useForm({
    name: '',
    email: '',
    phone: '',
    role: '',
    customer_tier: 'subscriber',
    status: 'active',
    password: '',
    password_confirmation: '',
    transaction_pin: '',
    transaction_pin_confirmation: '',
    is_banned: false,
    banned_services: [],
    ban_reason: '',
});
const apiClientForm = useForm({
    status: 'active',
    rate_limit_per_minute: 120,
    ip_whitelist: '',
});

const openCreate = () => {
    createUserForm.reset();
    createUserForm.role = props.assignableRoles?.includes('customer') ? 'customer' : (props.assignableRoles?.[0] || '');
    createUserForm.customer_tier = props.customerTiers?.includes('subscriber') ? 'subscriber' : (props.customerTiers?.[0] || '');
    createUserForm.status = 'active';
    createUserForm.transaction_pin = '';
    createUserForm.transaction_pin_confirmation = '';
    createUserForm.clearErrors();
    showCreateModal.value = true;
};

const openAdjust = (user, type = 'credit') => {
    selectedUser.value = user;
    adjustForm.reset();
    adjustForm.user_id = String(user.id);
    adjustForm.entry_type = type;
    adjustForm.amount = '';
    adjustForm.narration = type === 'credit' ? 'Admin manual funding' : 'Admin manual debit';
    adjustForm.reference = '';
    adjustForm.clearErrors();
    showAdjustModal.value = true;
};

const openEdit = (user) => {
    selectedUser.value = user;
    editUserForm.reset();
    editUserForm.name = user.name;
    editUserForm.email = user.email;
    editUserForm.phone = user.phone || '';
    editUserForm.role = (props.assignableRoles || []).includes(user.roles?.[0]) ? user.roles[0] : '';
    editUserForm.customer_tier = user.customer_tier || 'subscriber';
    editUserForm.status = user.status || 'active';
    editUserForm.password = '';
    editUserForm.password_confirmation = '';
    editUserForm.transaction_pin = '';
    editUserForm.transaction_pin_confirmation = '';
    editUserForm.is_banned = !!user.is_banned;
    editUserForm.banned_services = Array.isArray(user.banned_services) ? [...user.banned_services] : [];
    editUserForm.ban_reason = user.ban_reason || '';
    editUserForm.clearErrors();
    showEditModal.value = true;
};

const submitCreate = () => {
    createUserForm.post(route('admin.users.store'), {
        preserveScroll: true,
        onSuccess: () => {
            showCreateModal.value = false;
        },
    });
};

const submitEdit = () => {
    if (!selectedUser.value) return;

    editUserForm.put(route('admin.users.update', selectedUser.value.id), {
        preserveScroll: true,
        onSuccess: () => {
            showEditModal.value = false;
        },
    });
};

const submitAdjust = () => {
    if (!selectedUser.value) return;

    adjustForm.post(route('admin.users.wallet-adjust', selectedUser.value.id), {
        preserveScroll: true,
        onSuccess: () => {
            showAdjustModal.value = false;
        },
    });
};

const openApi = (user) => {
    selectedUser.value = user;
    const client = user.api_client || null;
    apiClientForm.reset();
    apiClientForm.status = client?.status || 'active';
    apiClientForm.rate_limit_per_minute = client?.rate_limit_per_minute || 120;
    apiClientForm.ip_whitelist = Array.isArray(client?.ip_whitelist) ? client.ip_whitelist.join('\n') : '';
    apiClientForm.clearErrors();
    showApiModal.value = true;
};

const submitApiClient = () => {
    if (!selectedUser.value) return;

    apiClientForm.put(route('admin.users.api-client.update', selectedUser.value.id), {
        preserveScroll: true,
        onSuccess: () => {
            showApiModal.value = false;
        },
    });
};

const rotateApiSecret = () => {
    if (!selectedUser.value) return;

    router.post(route('admin.users.api-client.rotate', selectedUser.value.id), {}, { preserveScroll: true });
};

const roleBadgeStatus = (role) => {
    if (['super-admin', 'admin'].includes(role)) return 'active';
    if (['support'].includes(role)) return 'pending';
    return 'hidden';
};

const tierBadgeClass = (tier) => {
    if (tier === 'agent') return 'bg-blue-50 text-blue-700 ring-blue-200';
    if (tier === 'reseller') return 'bg-violet-50 text-violet-700 ring-violet-200';
    return 'bg-slate-100 text-slate-700 ring-slate-200';
};

const selectedUserLabel = computed(() => {
    if (!selectedUser.value) return '';
    return `${selectedUser.value.name} (${selectedUser.value.email})`;
});

const adminApiSecretOnce = computed(() => page.props.flash?.admin_api_secret_once || null);
const copiedKey = ref('');
const activeTab = ref('users');

const pageTabs = computed(() => ([
    {
        key: 'users',
        label: 'Users',
        count: props.users?.total ?? props.users?.data?.length ?? 0,
    },
    {
        key: 'overview',
        label: 'Overview',
    },
    {
        key: 'ledger',
        label: 'Manual Adjustments',
        count: props.manualAdjustments?.length ?? 0,
    },
]));

const copyText = async (text, key) => {
    const value = String(text || '').trim();
    if (!value) return;

    try {
        if (navigator?.clipboard?.writeText) {
            await navigator.clipboard.writeText(value);
        }
    } catch {
        const textarea = document.createElement('textarea');
        textarea.value = value;
        textarea.setAttribute('readonly', '');
        textarea.style.position = 'absolute';
        textarea.style.left = '-9999px';
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
    }

    copiedKey.value = key;
    window.setTimeout(() => {
        if (copiedKey.value === key) copiedKey.value = '';
    }, 1200);
};
</script>

<template>
    <Head title="Users" />

    <AdminLayout>
        <template #header>
            <div class="flex items-center justify-between gap-4">
                <div>
                    <h2 class="text-xl font-semibold text-gray-800">Users</h2>
                    <p class="mt-1 text-sm text-gray-500">Manage user accounts and perform manual wallet funding/debit with ledger records.</p>
                </div>
                <div class="flex items-center gap-2">
                    <a
                        :href="route('admin.users.export-api-clients-csv', query)"
                        class="rounded-md border border-gray-300 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
                    >
                        Export API CSV
                    </a>
                    <PrimaryButton type="button" @click="openCreate">Add User</PrimaryButton>
                </div>
            </div>
        </template>

        <div class="mx-auto max-w-7xl space-y-6 px-4 py-6 sm:px-6 lg:px-8">
            <AppTabs v-model="activeTab" :tabs="pageTabs" aria-label="User sections" />

            <div v-if="activeTab === 'overview'" class="space-y-6">
                <AppCard
                    v-if="adminApiSecretOnce"
                    title="One-Time API Secret"
                    subtitle="Copy now. It will not be shown again."
                >
                    <div class="space-y-2 text-sm">
                        <div class="text-gray-700">
                            User: <span class="font-semibold">{{ adminApiSecretOnce.email }}</span>
                        </div>
                        <div class="rounded-md border border-gray-200 bg-gray-50 px-3 py-2 font-mono text-xs text-gray-700">
                            Public: {{ adminApiSecretOnce.public_key }}
                            <button
                                type="button"
                                class="ml-2 rounded border border-gray-300 bg-white px-2 py-0.5 text-[11px] font-semibold text-gray-700"
                                @click="copyText(adminApiSecretOnce.public_key, 'admin-public')"
                            >
                                {{ copiedKey === 'admin-public' ? 'Copied' : 'Copy' }}
                            </button>
                        </div>
                        <div class="rounded-md border border-emerald-200 bg-emerald-50 px-3 py-2 font-mono text-xs text-emerald-900">
                            Secret: {{ adminApiSecretOnce.secret }}
                            <button
                                type="button"
                                class="ml-2 rounded border border-emerald-300 bg-white px-2 py-0.5 text-[11px] font-semibold text-emerald-800"
                                @click="copyText(adminApiSecretOnce.secret, 'admin-secret')"
                            >
                                {{ copiedKey === 'admin-secret' ? 'Copied' : 'Copy' }}
                            </button>
                        </div>
                    </div>
                </AppCard>

                <div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
                    <AppCard title="Total Users" :subtitle="String(summary?.total_users ?? 0)" />
                    <AppCard title="Subscribers" :subtitle="String(summary?.subscribers ?? 0)" />
                    <AppCard title="Resellers / Agents" :subtitle="`${summary?.resellers ?? 0} / ${summary?.agents ?? 0}`" />
                    <AppCard title="Wallet Float" :subtitle="`NGN ${summary?.wallet_balance_total ?? 0}`" />
                </div>
            </div>

            <div v-if="activeTab === 'users'" class="space-y-6">
                <AppCard title="Filter Users">
                    <div class="grid gap-3 md:grid-cols-2 xl:grid-cols-[minmax(0,1fr)_170px_170px_160px_160px_auto]">
                        <input
                            v-model="query.q"
                            type="text"
                            placeholder="Search by name, email, or phone"
                            class="rounded-md border-gray-300 text-sm shadow-sm"
                        />
                        <select v-model="query.role" class="rounded-md border-gray-300 text-sm shadow-sm">
                            <option value="">All roles</option>
                            <option v-for="role in roles" :key="role" :value="role">{{ role }}</option>
                        </select>
                        <select v-model="query.customer_tier" class="rounded-md border-gray-300 text-sm shadow-sm">
                            <option value="">All tiers</option>
                            <option v-for="tier in customerTiers" :key="tier" :value="tier">{{ tier }}</option>
                        </select>
                        <select v-model="query.status" class="rounded-md border-gray-300 text-sm shadow-sm">
                            <option value="">All statuses</option>
                            <option v-for="status in statuses" :key="status" :value="status">{{ status }}</option>
                        </select>
                        <select v-model="query.api_status" class="rounded-md border-gray-300 text-sm shadow-sm">
                            <option value="">Any API status</option>
                            <option v-for="apiStatus in apiClientStatuses" :key="apiStatus" :value="apiStatus">{{ apiStatus }}</option>
                        </select>
                        <button type="button" class="rounded-md border border-gray-300 px-3 py-2 text-sm" @click="applyFilters">Apply</button>
                    </div>
                </AppCard>

                <AppCard title="User Management">
                    <AppTable>
                        <thead class="bg-gray-50">
                            <tr class="text-left text-xs font-semibold uppercase tracking-wide text-gray-500">
                                <th class="px-4 py-3">User</th>
                                <th class="px-4 py-3">Roles</th>
                                <th class="px-4 py-3">Tier / Status</th>
                                <th class="px-4 py-3">Wallet</th>
                                <th class="px-4 py-3">Activity</th>
                                <th class="px-4 py-3">Created</th>
                                <th class="px-4 py-3"></th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 text-sm">
                            <tr v-for="user in users.data" :key="user.id">
                                <td class="px-4 py-3">
                                    <div class="font-medium text-gray-900">{{ user.name }}</div>
                                    <div class="text-xs text-gray-500">{{ user.email }}</div>
                                    <div class="text-xs text-gray-500">{{ user.phone || '-' }}</div>
                                </td>
                                <td class="px-4 py-3">
                                    <div class="flex flex-wrap gap-1">
                                        <span
                                            v-for="role in (user.roles?.length ? user.roles : ['no-role'])"
                                            :key="`${user.id}-${role}`"
                                            class="inline-flex items-center rounded-full px-2 py-1 text-xs font-medium capitalize ring-1 ring-inset"
                                            :class="{
                                                'bg-emerald-50 text-emerald-700 ring-emerald-200': roleBadgeStatus(role) === 'active',
                                                'bg-amber-50 text-amber-700 ring-amber-200': roleBadgeStatus(role) === 'pending',
                                                'bg-slate-100 text-slate-700 ring-slate-200': roleBadgeStatus(role) === 'hidden',
                                            }"
                                        >
                                            {{ role.replaceAll('_', ' ') }}
                                        </span>
                                    </div>
                                </td>
                                <td class="px-4 py-3">
                                    <div class="flex flex-wrap items-center gap-1">
                                        <span
                                            class="inline-flex items-center rounded-full px-2 py-1 text-xs font-medium capitalize ring-1 ring-inset"
                                            :class="tierBadgeClass(user.customer_tier)"
                                        >
                                            {{ user.customer_tier || 'subscriber' }}
                                        </span>
                                        <StatusBadge :status="user.status || 'active'" />
                                        <span
                                            v-if="user.is_banned"
                                            class="inline-flex items-center rounded-full bg-rose-50 px-2 py-1 text-[11px] font-medium text-rose-700 ring-1 ring-inset ring-rose-200"
                                        >
                                            Banned
                                        </span>
                                        <span
                                            class="inline-flex items-center rounded-full px-2 py-1 text-[11px] font-medium ring-1 ring-inset"
                                            :class="user.has_transaction_pin ? 'bg-emerald-50 text-emerald-700 ring-emerald-200' : 'bg-amber-50 text-amber-700 ring-amber-200'"
                                        >
                                            {{ user.has_transaction_pin ? 'PIN set' : 'No PIN' }}
                                        </span>
                                    </div>
                                </td>
                                <td class="px-4 py-3">
                                    <div class="font-medium text-gray-900">NGN {{ user.wallet_balance }}</div>
                                    <div class="text-xs text-gray-500">{{ user.wallet_ledgers_count }} ledger entries</div>
                                </td>
                                <td class="px-4 py-3 text-xs text-gray-600">
                                    <div>Transactions: {{ user.transactions_count }}</div>
                                    <div>Reserved Accounts: {{ user.reserved_accounts_count }}</div>
                                </td>
                                <td class="px-4 py-3 text-xs text-gray-600">{{ user.created_at || '-' }}</td>
                                <td class="px-4 py-3">
                                    <div class="flex justify-end gap-2">
                                        <button
                                            type="button"
                                            class="rounded border border-gray-300 px-2.5 py-1 text-xs font-medium text-gray-700 hover:bg-gray-50"
                                            @click="openEdit(user)"
                                        >
                                            Edit
                                        </button>
                                        <button
                                            type="button"
                                            class="rounded border border-indigo-300 bg-indigo-50 px-2.5 py-1 text-xs font-medium text-indigo-700 hover:bg-indigo-100"
                                            @click="openApi(user)"
                                        >
                                            API
                                        </button>
                                        <button
                                            type="button"
                                            class="rounded border border-emerald-300 bg-emerald-50 px-2.5 py-1 text-xs font-medium text-emerald-700 hover:bg-emerald-100"
                                            @click="openAdjust(user, 'credit')"
                                        >
                                            Fund
                                        </button>
                                        <button
                                            type="button"
                                            class="rounded border border-rose-300 bg-rose-50 px-2.5 py-1 text-xs font-medium text-rose-700 hover:bg-rose-100"
                                            @click="openAdjust(user, 'debit')"
                                        >
                                            Debit
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <tr v-if="!users.data?.length">
                                <td colspan="7" class="px-4 py-8 text-center text-sm text-gray-500">No users found.</td>
                            </tr>
                        </tbody>
                    </AppTable>
                </AppCard>
            </div>

            <AppCard
                v-if="activeTab === 'ledger'"
                title="Recent Manual Wallet Adjustments"
                subtitle="Ledger-backed admin funding/debit history (source: admin_adjust)."
            >
                <AppTable>
                    <thead class="bg-gray-50">
                        <tr class="text-left text-xs font-semibold uppercase tracking-wide text-gray-500">
                            <th class="px-4 py-3">User</th>
                            <th class="px-4 py-3">Type</th>
                            <th class="px-4 py-3">Amount</th>
                            <th class="px-4 py-3">Balance Before/After</th>
                            <th class="px-4 py-3">Narration</th>
                            <th class="px-4 py-3">Reference</th>
                            <th class="px-4 py-3">Time</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100 text-sm">
                        <tr v-for="entry in manualAdjustments" :key="entry.id">
                            <td class="px-4 py-3">
                                <div class="font-medium text-gray-900">{{ entry.user?.name || 'Unknown' }}</div>
                                <div class="text-xs text-gray-500">{{ entry.user?.email }}</div>
                            </td>
                            <td class="px-4 py-3">
                                <div class="flex items-center gap-2">
                                    <StatusBadge :status="entry.entry_type === 'credit' ? 'success' : 'failed'" />
                                    <span class="text-xs font-medium text-gray-700 capitalize">{{ entry.entry_type }}</span>
                                </div>
                            </td>
                            <td class="px-4 py-3">NGN {{ entry.amount }}</td>
                            <td class="px-4 py-3 text-xs text-gray-600">
                                <div>{{ entry.balance_before }} -> {{ entry.balance_after }}</div>
                            </td>
                            <td class="px-4 py-3">
                                <div class="max-w-xs truncate text-xs text-gray-600">{{ entry.narration }}</div>
                            </td>
                            <td class="px-4 py-3">
                                <div class="max-w-xs truncate font-mono text-[11px] text-gray-600">{{ entry.reference }}</div>
                            </td>
                            <td class="px-4 py-3 text-xs text-gray-600">{{ entry.created_at || '-' }}</td>
                        </tr>
                        <tr v-if="!manualAdjustments?.length">
                            <td colspan="7" class="px-4 py-8 text-center text-sm text-gray-500">No manual wallet adjustments yet.</td>
                        </tr>
                    </tbody>
                </AppTable>
            </AppCard>
        </div>

        <AppModal :show="showCreateModal" title="Create User" @close="showCreateModal = false">
            <form class="space-y-4" @submit.prevent="submitCreate">
                <div class="grid gap-4 sm:grid-cols-2">
                    <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-gray-700">Name</label>
                        <input v-model="createUserForm.name" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm" />
                        <p v-if="createUserForm.errors.name" class="mt-1 text-xs text-rose-600">{{ createUserForm.errors.name }}</p>
                    </div>

                    <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-gray-700">Email</label>
                        <input v-model="createUserForm.email" type="email" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm" />
                        <p v-if="createUserForm.errors.email" class="mt-1 text-xs text-rose-600">{{ createUserForm.errors.email }}</p>
                    </div>

                    <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-gray-700">Phone Number</label>
                        <input
                            v-model="createUserForm.phone"
                            type="tel"
                            inputmode="numeric"
                            maxlength="15"
                            class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm"
                            placeholder="08012345678"
                        />
                        <p v-if="createUserForm.errors.phone" class="mt-1 text-xs text-rose-600">{{ createUserForm.errors.phone }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700">Password</label>
                        <input v-model="createUserForm.password" type="password" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm" />
                        <p v-if="createUserForm.errors.password" class="mt-1 text-xs text-rose-600">{{ createUserForm.errors.password }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700">Confirm Password</label>
                        <input v-model="createUserForm.password_confirmation" type="password" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm" />
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700">Transaction PIN (optional)</label>
                        <input v-model="createUserForm.transaction_pin" type="password" inputmode="numeric" maxlength="4" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm" placeholder="4 digits" />
                        <p v-if="createUserForm.errors.transaction_pin" class="mt-1 text-xs text-rose-600">{{ createUserForm.errors.transaction_pin }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700">Confirm Transaction PIN</label>
                        <input v-model="createUserForm.transaction_pin_confirmation" type="password" inputmode="numeric" maxlength="4" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm" placeholder="Repeat 4 digits" />
                    </div>

                    <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-gray-700">Role</label>
                        <select v-model="createUserForm.role" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm">
                            <option value="">No role</option>
                            <option v-for="role in assignableRoles" :key="role" :value="role">{{ role }}</option>
                        </select>
                        <p class="mt-1 text-xs text-gray-500">Only safe roles are allowed here. Admin/super-admin cannot be assigned from this screen.</p>
                        <p v-if="createUserForm.errors.role" class="mt-1 text-xs text-rose-600">{{ createUserForm.errors.role }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700">Customer Tier</label>
                        <select v-model="createUserForm.customer_tier" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm">
                            <option v-for="tier in customerTiers" :key="tier" :value="tier">{{ tier }}</option>
                        </select>
                        <p v-if="createUserForm.errors.customer_tier" class="mt-1 text-xs text-rose-600">{{ createUserForm.errors.customer_tier }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700">Status</label>
                        <select v-model="createUserForm.status" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm">
                            <option v-for="status in statuses" :key="status" :value="status">{{ status }}</option>
                        </select>
                        <p v-if="createUserForm.errors.status" class="mt-1 text-xs text-rose-600">{{ createUserForm.errors.status }}</p>
                    </div>
                </div>

                <div class="flex justify-end gap-2">
                    <button type="button" class="rounded border border-gray-300 px-3 py-2 text-sm" @click="showCreateModal = false">Cancel</button>
                    <PrimaryButton :disabled="createUserForm.processing">
                        {{ createUserForm.processing ? 'Creating...' : 'Create User' }}
                    </PrimaryButton>
                </div>
            </form>
        </AppModal>

        <AppModal :show="showAdjustModal" title="Manual Wallet Adjustment" @close="showAdjustModal = false">
            <form class="space-y-4" @submit.prevent="submitAdjust">
                <div class="rounded-lg border border-gray-200 bg-gray-50 px-3 py-2 text-sm text-gray-700">
                    <div class="font-medium text-gray-900">{{ selectedUserLabel }}</div>
                    <div class="text-xs text-gray-500">All adjustments are posted through wallet ledger (source: admin_adjust).</div>
                </div>

                <div class="grid gap-4 sm:grid-cols-2">
                    <div>
                        <label class="block text-sm font-medium text-gray-700">Type</label>
                        <select v-model="adjustForm.entry_type" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm">
                            <option value="credit">Credit (Fund)</option>
                            <option value="debit">Debit</option>
                        </select>
                        <p v-if="adjustForm.errors.entry_type" class="mt-1 text-xs text-rose-600">{{ adjustForm.errors.entry_type }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700">Amount</label>
                        <input v-model="adjustForm.amount" type="number" min="1" step="0.01" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm" />
                        <p v-if="adjustForm.errors.amount" class="mt-1 text-xs text-rose-600">{{ adjustForm.errors.amount }}</p>
                    </div>

                    <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-gray-700">Narration</label>
                        <input v-model="adjustForm.narration" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm" placeholder="e.g. Admin manual funding" />
                        <p v-if="adjustForm.errors.narration" class="mt-1 text-xs text-rose-600">{{ adjustForm.errors.narration }}</p>
                    </div>

                    <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-gray-700">Idempotency Reference (optional)</label>
                        <input
                            v-model="adjustForm.reference"
                            class="mt-1 w-full rounded-md border-gray-300 font-mono text-xs shadow-sm"
                            placeholder="Leave blank to auto-generate"
                        />
                        <p class="mt-1 text-xs text-gray-500">Provide a reference if you want safe retries without double funding/debiting.</p>
                        <p v-if="adjustForm.errors.reference" class="mt-1 text-xs text-rose-600">{{ adjustForm.errors.reference }}</p>
                    </div>
                </div>

                <div class="flex justify-end gap-2">
                    <button type="button" class="rounded border border-gray-300 px-3 py-2 text-sm" @click="showAdjustModal = false">Cancel</button>
                    <PrimaryButton :disabled="adjustForm.processing">
                        {{ adjustForm.processing ? 'Processing...' : (adjustForm.entry_type === 'credit' ? 'Fund Wallet' : 'Debit Wallet') }}
                    </PrimaryButton>
                </div>
            </form>
        </AppModal>

        <AppModal :show="showEditModal" title="Edit User / Upgrade Tier" @close="showEditModal = false">
            <form class="space-y-4" @submit.prevent="submitEdit">
                <div class="rounded-lg border border-gray-200 bg-gray-50 px-3 py-2 text-sm text-gray-700">
                    <div class="font-medium text-gray-900">{{ selectedUserLabel }}</div>
                    <div class="text-xs text-gray-500">Update user profile, tier (subscriber/reseller/agent), status, and optional password reset.</div>
                </div>

                <div class="grid gap-4 sm:grid-cols-2">
                    <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-gray-700">Name</label>
                        <input v-model="editUserForm.name" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm" />
                        <p v-if="editUserForm.errors.name" class="mt-1 text-xs text-rose-600">{{ editUserForm.errors.name }}</p>
                    </div>

                    <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-gray-700">Email</label>
                        <input v-model="editUserForm.email" type="email" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm" />
                        <p v-if="editUserForm.errors.email" class="mt-1 text-xs text-rose-600">{{ editUserForm.errors.email }}</p>
                    </div>

                    <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-gray-700">Phone Number</label>
                        <input
                            v-model="editUserForm.phone"
                            type="tel"
                            inputmode="numeric"
                            maxlength="15"
                            class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm"
                            placeholder="08012345678"
                        />
                        <p v-if="editUserForm.errors.phone" class="mt-1 text-xs text-rose-600">{{ editUserForm.errors.phone }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700">Customer Tier</label>
                        <select v-model="editUserForm.customer_tier" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm">
                            <option v-for="tier in customerTiers" :key="tier" :value="tier">{{ tier }}</option>
                        </select>
                        <p v-if="editUserForm.errors.customer_tier" class="mt-1 text-xs text-rose-600">{{ editUserForm.errors.customer_tier }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700">Status</label>
                        <select v-model="editUserForm.status" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm">
                            <option v-for="status in statuses" :key="status" :value="status">{{ status }}</option>
                        </select>
                        <p v-if="editUserForm.errors.status" class="mt-1 text-xs text-rose-600">{{ editUserForm.errors.status }}</p>
                    </div>

                    <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-gray-700">Primary Role (safe roles only)</label>
                        <select v-model="editUserForm.role" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm">
                            <option value="">Keep current roles</option>
                            <option v-for="role in assignableRoles" :key="role" :value="role">{{ role }}</option>
                        </select>
                        <p class="mt-1 text-xs text-gray-500">For security, admin/super-admin are not assignable from this screen. Tier pricing uses Customer Tier, not this role.</p>
                        <p v-if="editUserForm.errors.role" class="mt-1 text-xs text-rose-600">{{ editUserForm.errors.role }}</p>
                    </div>

                    <div class="sm:col-span-2 rounded-lg border border-gray-200 bg-gray-50 p-3">
                        <div class="flex items-center justify-between gap-3">
                            <label class="text-sm font-medium text-gray-800">Total Ban</label>
                            <input v-model="editUserForm.is_banned" type="checkbox" class="rounded border-gray-300 text-rose-600" />
                        </div>
                        <p class="mt-1 text-xs text-gray-500">If enabled, user cannot transact on any service.</p>
                    </div>

                    <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-gray-700">Ban Specific Services</label>
                        <div class="mt-2 grid gap-2 sm:grid-cols-2">
                            <label
                                v-for="service in banServiceKeys"
                                :key="service"
                                class="inline-flex items-center gap-2 rounded-md border border-gray-200 bg-white px-2.5 py-2 text-xs capitalize text-gray-700"
                            >
                                <input
                                    v-model="editUserForm.banned_services"
                                    type="checkbox"
                                    class="rounded border-gray-300"
                                    :value="service"
                                />
                                {{ service.replace('_', ' ') }}
                            </label>
                        </div>
                        <p v-if="editUserForm.errors.banned_services" class="mt-1 text-xs text-rose-600">{{ editUserForm.errors.banned_services }}</p>
                    </div>

                    <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-gray-700">Ban Reason (optional)</label>
                        <input v-model="editUserForm.ban_reason" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm" />
                        <p v-if="editUserForm.errors.ban_reason" class="mt-1 text-xs text-rose-600">{{ editUserForm.errors.ban_reason }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700">New Password (optional)</label>
                        <input v-model="editUserForm.password" type="password" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm" />
                        <p v-if="editUserForm.errors.password" class="mt-1 text-xs text-rose-600">{{ editUserForm.errors.password }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700">Confirm New Password</label>
                        <input v-model="editUserForm.password_confirmation" type="password" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm" />
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700">Reset Transaction PIN (optional)</label>
                        <input v-model="editUserForm.transaction_pin" type="password" inputmode="numeric" maxlength="4" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm" placeholder="4 digits" />
                        <p class="mt-1 text-xs text-gray-500">Leave blank to keep current PIN.</p>
                        <p v-if="editUserForm.errors.transaction_pin" class="mt-1 text-xs text-rose-600">{{ editUserForm.errors.transaction_pin }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700">Confirm Transaction PIN</label>
                        <input v-model="editUserForm.transaction_pin_confirmation" type="password" inputmode="numeric" maxlength="4" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm" placeholder="Repeat 4 digits" />
                    </div>
                </div>

                <div class="flex justify-end gap-2">
                    <button type="button" class="rounded border border-gray-300 px-3 py-2 text-sm" @click="showEditModal = false">Cancel</button>
                    <PrimaryButton :disabled="editUserForm.processing">
                        {{ editUserForm.processing ? 'Saving...' : 'Save User' }}
                    </PrimaryButton>
                </div>
            </form>
        </AppModal>

        <AppModal :show="showApiModal" title="Manage User API Client" @close="showApiModal = false">
            <form class="space-y-4" @submit.prevent="submitApiClient">
                <div class="rounded-lg border border-gray-200 bg-gray-50 px-3 py-2 text-sm text-gray-700">
                    <div class="font-medium text-gray-900">{{ selectedUserLabel }}</div>
                    <div class="text-xs text-gray-500">Configure API access policy and rotate API secret for this user.</div>
                </div>

                <div class="grid gap-4 sm:grid-cols-2">
                    <div class="sm:col-span-2 rounded-lg border border-gray-200 bg-white p-3">
                        <div class="text-xs text-gray-500">Public Key</div>
                        <div class="mt-1 break-all font-mono text-xs text-gray-800">{{ selectedUser?.api_client?.public_key || 'Will be generated automatically' }}</div>
                        <div class="mt-1 text-xs text-gray-500">
                            Secret last4: <span class="font-semibold">{{ selectedUser?.api_client?.secret_last4 || '----' }}</span>
                            <span class="mx-2">|</span>
                            Last used: {{ selectedUser?.api_client?.last_used_at || 'Never' }}
                        </div>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700">Client Status</label>
                        <select v-model="apiClientForm.status" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm">
                            <option value="active">active</option>
                            <option value="inactive">inactive</option>
                        </select>
                        <p v-if="apiClientForm.errors.status" class="mt-1 text-xs text-rose-600">{{ apiClientForm.errors.status }}</p>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700">Rate Limit / Minute</label>
                        <input v-model="apiClientForm.rate_limit_per_minute" type="number" min="10" max="2000" class="mt-1 w-full rounded-md border-gray-300 text-sm shadow-sm" />
                        <p v-if="apiClientForm.errors.rate_limit_per_minute" class="mt-1 text-xs text-rose-600">{{ apiClientForm.errors.rate_limit_per_minute }}</p>
                    </div>

                    <div class="sm:col-span-2">
                        <label class="block text-sm font-medium text-gray-700">IP Whitelist (optional)</label>
                        <textarea
                            v-model="apiClientForm.ip_whitelist"
                            rows="4"
                            class="mt-1 w-full rounded-md border-gray-300 text-xs font-mono shadow-sm"
                            placeholder="One IP per line or comma separated. Leave empty to allow all IPs."
                        />
                        <p class="mt-1 text-xs text-gray-500">If set, requests from other IPs are blocked.</p>
                        <p v-if="apiClientForm.errors.ip_whitelist" class="mt-1 text-xs text-rose-600">{{ apiClientForm.errors.ip_whitelist }}</p>
                    </div>
                </div>

                <div class="flex flex-wrap items-center justify-between gap-2">
                    <button
                        type="button"
                        class="rounded border border-amber-300 bg-amber-50 px-3 py-2 text-xs font-semibold text-amber-800 hover:bg-amber-100"
                        @click="rotateApiSecret"
                    >
                        Rotate Secret
                    </button>

                    <div class="flex gap-2">
                        <button type="button" class="rounded border border-gray-300 px-3 py-2 text-sm" @click="showApiModal = false">Cancel</button>
                        <PrimaryButton :disabled="apiClientForm.processing">
                            {{ apiClientForm.processing ? 'Saving...' : 'Save API Settings' }}
                        </PrimaryButton>
                    </div>
                </div>
            </form>
        </AppModal>
    </AdminLayout>
</template>
