<template>
    <div class="space-y-6">
        <Head title="Client Directory" />

        <div class="rounded-2xl border border-slate-200 bg-white p-6">
            <div class="flex flex-wrap items-start justify-between gap-4">
                <div>
                    <h2 class="text-lg font-semibold">Client Directory</h2>
                    <p class="text-sm text-slate-500">
                        Search, filter, and manage client profiles.
                    </p>
                </div>
            </div>

            <div class="mt-6 grid gap-3 lg:grid-cols-4">
                <div>
                    <label class="text-xs font-semibold uppercase text-slate-400">
                        Search
                    </label>
                    <input
                        v-model="search"
                        type="text"
                        class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        placeholder="Search name, code, email, or mobile..."
                    />
                </div>
                <div>
                    <label class="text-xs font-semibold uppercase text-slate-400">
                        Status
                    </label>
                    <select
                        v-model="statusFilter"
                        class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                    >
                        <option value="all">All status</option>
                        <option value="pending">Pending</option>
                        <option value="verified">Verified</option>
                        <option value="rejected">Rejected</option>
                    </select>
                </div>
                <div>
                    <label class="text-xs font-semibold uppercase text-slate-400">
                        Type
                    </label>
                    <select
                        v-model="typeFilter"
                        class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                    >
                        <option value="all">All types</option>
                        <option value="individual">Individual</option>
                        <option value="corporate">Corporate</option>
                    </select>
                </div>
                <div class="flex items-end gap-2">
                    <button
                        class="rounded-lg border border-slate-200 px-3 py-2 text-xs font-semibold text-slate-600"
                        type="button"
                        @click="resetFilters"
                    >
                        Clear
                    </button>
                </div>
            </div>

            <div class="mt-6 grid gap-4 sm:grid-cols-6">
                <div class="rounded-xl border border-slate-100 p-4">
                    <p class="text-xs text-slate-400">Total</p>
                    <p class="mt-2 text-lg font-semibold">{{ totalCount }}</p>
                </div>
                <div class="rounded-xl border border-slate-100 p-4">
                    <p class="text-xs text-slate-400">Verified</p>
                    <p class="mt-2 text-lg font-semibold text-emerald-700">
                        {{ verifiedCount }}
                    </p>
                </div>
                <div class="rounded-xl border border-slate-100 p-4">
                    <p class="text-xs text-slate-400">Pending</p>
                    <p class="mt-2 text-lg font-semibold text-amber-600">
                        {{ pendingCount }}
                    </p>
                </div>
                <div class="rounded-xl border border-slate-100 p-4">
                    <p class="text-xs text-slate-400">Rejected</p>
                    <p class="mt-2 text-lg font-semibold text-rose-600">
                        {{ rejectedCount }}
                    </p>
                </div>
            </div>

            <div class="mt-6 overflow-hidden rounded-lg border border-slate-100">
                <table class="w-full text-left text-sm">
                    <thead class="bg-slate-50 text-slate-500">
                        <tr>
                            <th class="px-4 py-3">Client</th>
                            <th class="px-4 py-3">Type</th>
                            <th class="px-4 py-3">Status</th>
                            <th class="px-4 py-3">Accounts</th>
                            <th class="px-4 py-3">Created</th>
                            <th class="px-4 py-3 text-right">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr
                            v-for="client in pagedClients"
                            :key="client.uuid"
                            class="border-t border-slate-100"
                        >
                            <td class="px-4 py-3">
                                <div class="flex items-center gap-3">
                                    <span
                                        class="flex h-9 w-9 items-center justify-center rounded-full bg-slate-100 text-xs font-semibold text-slate-600"
                                    >
                                        {{ initials(client.full_name) }}
                                    </span>
                                    <div>
                                        <p class="font-semibold text-slate-700">
                                            {{ client.full_name }}
                                        </p>
                                        <p class="text-xs text-slate-400">
                                            {{ client.client_code }}
                                        </p>
                                    </div>
                                </div>
                            </td>
                            <td class="px-4 py-3 capitalize text-slate-600">
                                {{ client.type }}
                            </td>
                            <td class="px-4 py-3">
                                <span
                                    class="rounded-full px-2 py-1 text-xs font-semibold"
                                    :class="statusClass(client.status)"
                                >
                                    {{ statusLabel(client.status) }}
                                </span>
                            </td>
                            <td class="px-4 py-3 text-slate-500">
                                {{ client.accounts_count }}
                            </td>
                            <td class="px-4 py-3 text-slate-500">
                                {{ client.created_at || '—' }}
                            </td>
                            <td class="px-4 py-3 text-right">
                                <div class="flex justify-end gap-2">
                                    <button
                                        class="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-700 hover:bg-slate-50"
                                        type="button"
                                        @click="openView(client)"
                                    >
                                        View
                                    </button>
                                    <button
                                        v-if="canEditClient"
                                        class="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-700 hover:bg-slate-50"
                                        type="button"
                                        @click="openEdit(client)"
                                    >
                                        Edit
                                    </button>
                                </div>
                            </td>
                        </tr>
                        <tr v-if="pagedClients.length === 0">
                            <td
                                class="px-4 py-6 text-center text-sm text-slate-500"
                                colspan="6"
                            >
                                No clients found.
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div
                class="mt-6 flex flex-wrap items-center justify-between gap-3 text-sm text-slate-500"
            >
                <div>
                    Showing {{ pageStart }} to {{ pageEnd }} of
                    {{ totalCount }} clients
                </div>
                <div class="flex items-center gap-2">
                    <label class="text-xs uppercase text-slate-400">Rows</label>
                    <select
                        v-model.number="perPage"
                        class="rounded-lg border border-slate-200 px-2 py-1 text-xs"
                    >
                        <option :value="5">5</option>
                        <option :value="10">10</option>
                        <option :value="20">20</option>
                    </select>
                    <button
                        class="rounded-lg border border-slate-200 px-2 py-1 text-xs"
                        type="button"
                        :disabled="page === 1"
                        @click="page--"
                    >
                        Prev
                    </button>
                    <span class="text-xs">{{ page }} / {{ totalPages }}</span>
                    <button
                        class="rounded-lg border border-slate-200 px-2 py-1 text-xs"
                        type="button"
                        :disabled="page === totalPages"
                        @click="page++"
                    >
                        Next
                    </button>
                </div>
            </div>
        </div>

        <div
            v-if="showViewModal"
            class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
        >
            <div class="w-full max-w-2xl rounded-2xl bg-white p-6">
                <div class="flex items-start justify-between gap-4">
                    <div>
                        <h3 class="text-lg font-semibold">Client Details</h3>
                        <p class="text-sm text-slate-500">
                            Full profile information.
                        </p>
                    </div>
                    <div class="flex items-center gap-2">
                        <button
                            class="rounded-lg border border-slate-200 px-2 py-1 text-xs text-slate-600 hover:bg-slate-50"
                            type="button"
                            @click="openCards"
                        >
                            View Cards
                        </button>
                        <button
                            class="rounded-lg border border-slate-200 px-2 py-1 text-xs text-slate-500"
                            type="button"
                            @click="closeView"
                        >
                            Close
                        </button>
                    </div>
                </div>

                <div class="mt-6 grid gap-4 md:grid-cols-2">
                    <div>
                        <p class="text-xs uppercase text-slate-400">Name</p>
                        <p class="mt-1 text-sm font-semibold text-slate-700">
                            {{ selectedClient.full_name }}
                        </p>
                    </div>
                    <div>
                        <p class="text-xs uppercase text-slate-400">Client Code</p>
                        <p class="mt-1 text-sm text-slate-600">
                            {{ selectedClient.client_code || '—' }}
                        </p>
                    </div>
                    <div>
                        <p class="text-xs uppercase text-slate-400">Email</p>
                        <p class="mt-1 text-sm text-slate-600">
                            {{ selectedClient.email || '—' }}
                        </p>
                    </div>
                    <div>
                        <p class="text-xs uppercase text-slate-400">Mobile</p>
                        <p class="mt-1 text-sm text-slate-600">
                            {{ selectedClient.mobile || '—' }}
                        </p>
                    </div>
                    <div>
                        <p class="text-xs uppercase text-slate-400">Birth Date</p>
                        <p class="mt-1 text-sm text-slate-600">
                            {{ selectedClient.birth_date || '—' }}
                        </p>
                    </div>
                    <div>
                        <p class="text-xs uppercase text-slate-400">Type</p>
                        <p class="mt-1 text-sm text-slate-600 capitalize">
                            {{ selectedClient.type || '—' }}
                        </p>
                    </div>
                    <div>
                        <p class="text-xs uppercase text-slate-400">Status</p>
                        <p class="mt-1 text-sm text-slate-600 capitalize">
                            {{ selectedClient.status || '—' }}
                        </p>
                    </div>
                    <div>
                        <p class="text-xs uppercase text-slate-400">KYC Level</p>
                        <p class="mt-1 text-sm text-slate-600">
                            {{ selectedClient.kyc_level || '—' }}
                        </p>
                    </div>
                    <div class="md:col-span-2">
                        <p class="text-xs uppercase text-slate-400">Address</p>
                        <p class="mt-1 text-sm text-slate-600">
                            {{ selectedClient.address || '—' }}
                        </p>
                    </div>
                    <div class="md:col-span-2">
                        <div class="mt-2 rounded-xl border border-slate-100 bg-slate-50 p-4">
                            <p class="text-xs font-semibold uppercase text-slate-400">
                                KYC Verification
                            </p>
                            <div v-if="!selectedClient.kyc" class="mt-2 text-sm text-slate-500">
                                No KYC submission found.
                            </div>
                            <div v-else class="mt-3 grid gap-3 md:grid-cols-2">
                                <div>
                                    <p class="text-xs uppercase text-slate-400">Status</p>
                                    <p class="mt-1 text-sm text-slate-600 capitalize">
                                        {{ selectedClient.kyc.status || '—' }}
                                    </p>
                                </div>
                                <div>
                                    <p class="text-xs uppercase text-slate-400">ID Type</p>
                                    <p class="mt-1 text-sm text-slate-600">
                                        {{ selectedClient.kyc.id_type || '—' }}
                                    </p>
                                </div>
                                <div>
                                    <p class="text-xs uppercase text-slate-400">ID Number</p>
                                    <p class="mt-1 text-sm text-slate-600">
                                        {{ selectedClient.kyc.id_number || '—' }}
                                    </p>
                                </div>
                                <div>
                                    <p class="text-xs uppercase text-slate-400">Submitted</p>
                                    <p class="mt-1 text-sm text-slate-600">
                                        {{ selectedClient.kyc.submitted_at || '—' }}
                                    </p>
                                </div>
                                <div>
                                    <p class="text-xs uppercase text-slate-400">Reviewed By</p>
                                    <p class="mt-1 text-sm text-slate-600">
                                        {{ selectedClient.kyc.reviewed_by || '—' }}
                                    </p>
                                </div>
                                <div>
                                    <p class="text-xs uppercase text-slate-400">Reviewed At</p>
                                    <p class="mt-1 text-sm text-slate-600">
                                        {{ selectedClient.kyc.reviewed_at || '—' }}
                                    </p>
                                </div>
                                <div class="md:col-span-2">
                                    <p class="text-xs uppercase text-slate-400">Remarks</p>
                                    <p class="mt-1 text-sm text-slate-600">
                                        {{ selectedClient.kyc.remarks || '—' }}
                                    </p>
                                </div>
                                <div class="md:col-span-2">
                                    <p class="text-xs uppercase text-slate-400">Documents</p>
                                    <div class="mt-2 flex flex-wrap gap-3 text-sm">
                                        <button
                                            v-if="selectedClient.kyc.documents?.id_front"
                                            class="text-emerald-700 hover:underline"
                                            type="button"
                                            @click="
                                                openDocument(
                                                    selectedClient.kyc.id,
                                                    'id_front',
                                                    'ID Front'
                                                )
                                            "
                                        >
                                            ID Front
                                        </button>
                                        <button
                                            v-if="selectedClient.kyc.documents?.id_back"
                                            class="text-emerald-700 hover:underline"
                                            type="button"
                                            @click="
                                                openDocument(
                                                    selectedClient.kyc.id,
                                                    'id_back',
                                                    'ID Back'
                                                )
                                            "
                                        >
                                            ID Back
                                        </button>
                                        <button
                                            v-if="selectedClient.kyc.documents?.selfie"
                                            class="text-emerald-700 hover:underline"
                                            type="button"
                                            @click="
                                                openDocument(
                                                    selectedClient.kyc.id,
                                                    'selfie',
                                                    'Selfie'
                                                )
                                            "
                                        >
                                            Selfie
                                        </button>
                                        <span
                                            v-if="
                                                !selectedClient.kyc.documents?.id_front &&
                                                !selectedClient.kyc.documents?.id_back &&
                                                !selectedClient.kyc.documents?.selfie
                                            "
                                            class="text-slate-500"
                                        >
                                            No documents uploaded.
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div
            v-if="showCardsModal"
            class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
        >
            <div class="w-full max-w-5xl rounded-2xl bg-white p-6">
                <div class="flex items-start justify-between gap-4">
                    <div>
                        <h3 class="text-lg font-semibold">Linked Cards</h3>
                        <p class="text-sm text-slate-500">
                            Card details linked to {{ selectedClient.full_name || 'this client' }}.
                        </p>
                    </div>
                    <button
                        class="rounded-lg border border-slate-200 px-2 py-1 text-xs text-slate-500"
                        type="button"
                        @click="closeCards"
                    >
                        Close
                    </button>
                </div>

                <div class="mt-4 overflow-hidden rounded-xl border border-slate-100">
                    <div class="overflow-x-auto">
                        <table class="w-full min-w-[1200px] text-left text-xs">
                        <thead class="bg-slate-50 text-slate-500">
                            <tr>
                                <th class="px-4 py-3">Card Number</th>
                                <th class="px-4 py-3">Type</th>
                                <th class="px-4 py-3">Status</th>
                                <th class="px-4 py-3">Account</th>
                                <th class="px-4 py-3">Institution</th>
                                <th class="px-4 py-3">Product</th>
                                <th class="px-4 py-3">Batch</th>
                                <th class="px-4 py-3">Expiry</th>
                                    <th class="px-4 py-3">Print Status</th>
                                    <th class="px-4 py-3">Printer</th>
                                    <th class="px-4 py-3">Printed At</th>
                                    <th class="px-4 py-3">Pin Status</th>
                                    <th class="px-4 py-3">Pin Generated</th>
                                    <th class="px-4 py-3">Pin Dispatched</th>
                                <th class="px-4 py-3">Created</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr
                                v-for="card in selectedClient.cards || []"
                                :key="card.uuid"
                                class="border-t border-slate-100"
                            >
                                <td class="px-4 py-3 font-medium text-slate-700">
                                    {{ card.card_number || '—' }}
                                </td>
                                <td class="px-4 py-3 text-slate-500">
                                    {{ card.card_type || '—' }}
                                </td>
                                <td class="px-4 py-3">
                                    <span
                                        class="rounded-full px-2 py-1 text-[10px] font-semibold"
                                        :class="cardStatusClass(card.status)"
                                    >
                                        {{ card.status || '—' }}
                                    </span>
                                </td>
                                <td class="px-4 py-3 text-slate-500">
                                    {{ card.account?.account_number || '—' }}
                                </td>
                                <td class="px-4 py-3 text-slate-500">
                                    {{ card.institution?.name || '—' }}
                                </td>
                                <td class="px-4 py-3 text-slate-500">
                                    {{ card.product?.name || '—' }}
                                </td>
                                <td class="px-4 py-3 text-slate-500">
                                    {{ card.batch?.id || '—' }}
                                </td>
                                <td class="px-4 py-3 text-slate-500">
                                    {{ formatExpiry(card) }}
                                </td>
                                <td class="px-4 py-3 text-slate-500">
                                    {{ card.print_job?.status || '—' }}
                                </td>
                                <td class="px-4 py-3 text-slate-500">
                                    {{ card.print_job?.printer?.name || '—' }}
                                </td>
                                <td class="px-4 py-3 text-slate-500">
                                    {{ card.print_job?.printed_at || '—' }}
                                </td>
                                <td class="px-4 py-3 text-slate-500">
                                    {{ card.pin_mailer?.status || '—' }}
                                </td>
                                <td class="px-4 py-3 text-slate-500">
                                    {{ card.pin_mailer?.generated_at || '—' }}
                                </td>
                                <td class="px-4 py-3 text-slate-500">
                                    {{ card.pin_mailer?.dispatched_at || '—' }}
                                </td>
                                <td class="px-4 py-3 text-slate-500">
                                    {{ card.created_at || '—' }}
                                </td>
                            </tr>
                            <tr v-if="(selectedClient.cards || []).length === 0">
                                <td
                                    class="px-4 py-6 text-center text-xs text-slate-400"
                                    colspan="15"
                                >
                                    No linked cards found for this client.
                                </td>
                            </tr>
                        </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div
            v-if="showDocumentModal"
            class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
        >
            <div class="w-full max-w-4xl rounded-2xl bg-white p-6">
                <div class="flex items-start justify-between gap-4">
                    <div>
                        <h3 class="text-lg font-semibold">{{ selectedDocumentLabel }}</h3>
                        <p class="text-sm text-slate-500">
                            Review the uploaded document.
                        </p>
                    </div>
                    <button
                        class="rounded-lg border border-slate-200 px-2 py-1 text-xs text-slate-500"
                        type="button"
                        @click="closeDocument"
                    >
                        Close
                    </button>
                </div>

                <div class="mt-4 overflow-hidden rounded-xl border border-slate-100">
                    <iframe
                        :src="selectedDocumentUrl"
                        class="h-[70vh] w-full"
                        title="KYC Document Preview"
                    ></iframe>
                </div>

                <div class="mt-4 flex justify-end">
                    <a
                        class="rounded-lg border border-slate-200 px-4 py-2 text-xs font-semibold text-slate-700"
                        :href="selectedDocumentUrl"
                        target="_blank"
                        rel="noreferrer"
                    >
                        Open in new tab
                    </a>
                </div>
            </div>
        </div>

        <div
            v-if="showEditModal"
            class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
        >
            <div class="w-full max-w-2xl rounded-2xl bg-white p-6">
                <div class="flex items-start justify-between gap-4">
                    <div>
                        <h3 class="text-lg font-semibold">Edit Client</h3>
                        <p class="text-sm text-slate-500">
                            Update client details and KYC status.
                        </p>
                    </div>
                    <button
                        class="rounded-lg border border-slate-200 px-2 py-1 text-xs text-slate-500"
                        type="button"
                        @click="closeEdit"
                    >
                        Close
                    </button>
                </div>

                <form class="mt-6 grid gap-4 md:grid-cols-2" @submit.prevent="submit">
                    <div>
                        <label class="text-sm font-medium">Client Code</label>
                        <input
                            v-model="form.client_code"
                            type="text"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                            readonly
                        />
                    </div>
                    <div>
                        <label class="text-sm font-medium">Type</label>
                        <select
                            v-model="form.type"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        >
                            <option value="individual">Individual</option>
                            <option value="corporate">Corporate</option>
                        </select>
                        <p v-if="form.errors.type" class="mt-1 text-xs text-red-600">
                            {{ form.errors.type }}
                        </p>
                    </div>
                    <div>
                        <label class="text-sm font-medium">First Name</label>
                        <input
                            v-model="form.first_name"
                            type="text"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        />
                        <p
                            v-if="form.errors.first_name"
                            class="mt-1 text-xs text-red-600"
                        >
                            {{ form.errors.first_name }}
                        </p>
                    </div>
                    <div>
                        <label class="text-sm font-medium">Last Name</label>
                        <input
                            v-model="form.last_name"
                            type="text"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        />
                        <p
                            v-if="form.errors.last_name"
                            class="mt-1 text-xs text-red-600"
                        >
                            {{ form.errors.last_name }}
                        </p>
                    </div>
                    <div>
                        <label class="text-sm font-medium">Birth Date</label>
                        <input
                            v-model="form.birth_date"
                            type="date"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        />
                        <p
                            v-if="form.errors.birth_date"
                            class="mt-1 text-xs text-red-600"
                        >
                            {{ form.errors.birth_date }}
                        </p>
                    </div>
                    <div>
                        <label class="text-sm font-medium">Email</label>
                        <input
                            v-model="form.email"
                            type="email"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        />
                        <p v-if="form.errors.email" class="mt-1 text-xs text-red-600">
                            {{ form.errors.email }}
                        </p>
                    </div>
                    <div>
                        <label class="text-sm font-medium">Mobile</label>
                        <input
                            v-model="form.mobile"
                            type="text"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        />
                        <p v-if="form.errors.mobile" class="mt-1 text-xs text-red-600">
                            {{ form.errors.mobile }}
                        </p>
                    </div>
                    <div>
                        <label class="text-sm font-medium">Status</label>
                        <select
                            v-model="form.status"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        >
                            <option value="pending">Pending</option>
                            <option value="verified">Verified</option>
                            <option value="rejected">Rejected</option>
                        </select>
                        <p v-if="form.errors.status" class="mt-1 text-xs text-red-600">
                            {{ form.errors.status }}
                        </p>
                    </div>
                    <div>
                        <label class="text-sm font-medium">KYC Level</label>
                        <input
                            v-model="form.kyc_level"
                            type="text"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                            placeholder="Optional"
                        />
                        <p v-if="form.errors.kyc_level" class="mt-1 text-xs text-red-600">
                            {{ form.errors.kyc_level }}
                        </p>
                    </div>
                    <div class="md:col-span-2">
                        <label class="text-sm font-medium">Address</label>
                        <textarea
                            v-model="form.address"
                            rows="3"
                            class="mt-2 w-full rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        ></textarea>
                        <p v-if="form.errors.address" class="mt-1 text-xs text-red-600">
                            {{ form.errors.address }}
                        </p>
                    </div>
                    <div class="md:col-span-2 flex justify-end gap-2">
                        <button
                            class="rounded-lg border border-slate-200 px-4 py-2 text-xs font-semibold text-slate-700"
                            type="button"
                            @click="closeEdit"
                        >
                            Cancel
                        </button>
                        <button
                            class="rounded-lg bg-slate-900 px-4 py-2 text-xs font-semibold text-white"
                            type="submit"
                            :disabled="form.processing"
                        >
                            Save Changes
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue';
import { Head, useForm } from '@inertiajs/vue3';
import AuthenticatedLayout from '../../Layouts/AuthenticatedLayout.vue';

defineOptions({
    layout: (h, page) =>
        h(AuthenticatedLayout, { title: 'Client Directory' }, () => page),
});

const props = defineProps({
    clients: {
        type: Array,
        default: () => [],
    },
    canEditClient: {
        type: Boolean,
        default: false,
    },
});

const search = ref('');
const statusFilter = ref('all');
const typeFilter = ref('all');
const perPage = ref(10);
const page = ref(1);

const form = useForm({
    uuid: null,
    client_code: '',
    type: 'individual',
    first_name: '',
    last_name: '',
    birth_date: '',
    email: '',
    mobile: '',
    address: '',
    status: 'pending',
    kyc_level: '',
    full_name: '',
});

const showEditModal = ref(false);
const showViewModal = ref(false);
const showCardsModal = ref(false);
const selectedClient = ref({});
const showDocumentModal = ref(false);
const selectedDocumentUrl = ref('');
const selectedDocumentLabel = ref('Document');

const filteredClients = computed(() => {
    const term = search.value.trim().toLowerCase();
    return props.clients.filter((client) => {
        const matchesSearch = term
            ? [client.full_name, client.client_code, client.email, client.mobile]
                  .filter(Boolean)
                  .some((value) => value.toLowerCase().includes(term))
            : true;
        const matchesStatus =
            statusFilter.value === 'all'
                ? true
                : client.status === statusFilter.value;
        const matchesType =
            typeFilter.value === 'all' ? true : client.type === typeFilter.value;
        return matchesSearch && matchesStatus && matchesType;
    });
});

const totalCount = computed(() => filteredClients.value.length);
const verifiedCount = computed(
    () => filteredClients.value.filter((client) => client.status === 'verified').length
);
const pendingCount = computed(
    () => filteredClients.value.filter((client) => client.status === 'pending').length
);
const rejectedCount = computed(
    () => filteredClients.value.filter((client) => client.status === 'rejected').length
);

const totalPages = computed(() =>
    Math.max(1, Math.ceil(totalCount.value / perPage.value))
);
const pageStart = computed(() =>
    totalCount.value === 0 ? 0 : (page.value - 1) * perPage.value + 1
);
const pageEnd = computed(() =>
    Math.min(page.value * perPage.value, totalCount.value)
);
const pagedClients = computed(() =>
    filteredClients.value.slice(
        (page.value - 1) * perPage.value,
        page.value * perPage.value
    )
);

watch([search, statusFilter, typeFilter, perPage], () => {
    page.value = 1;
});

watch(filteredClients, () => {
    if (page.value > totalPages.value) {
        page.value = totalPages.value;
    }
});

const resetFilters = () => {
    search.value = '';
    statusFilter.value = 'all';
    typeFilter.value = 'all';
};

const openView = (client) => {
    selectedClient.value = { ...client };
    showViewModal.value = true;
};

const closeView = () => {
    showViewModal.value = false;
    closeCards();
    closeDocument();
};

const openCards = () => {
    showCardsModal.value = true;
};

const closeCards = () => {
    showCardsModal.value = false;
};

const openEdit = (client) => {
    form.clearErrors();
    form.uuid = client.uuid;
    form.client_code = client.client_code;
    form.type = client.type || 'individual';
    form.first_name = client.first_name;
    form.last_name = client.last_name;
    form.birth_date = client.birth_date;
    form.email = client.email;
    form.mobile = client.mobile;
    form.address = client.address;
    form.status = client.status || 'pending';
    form.kyc_level = client.kyc_level || '';
    form.full_name = client.full_name || '';
    showEditModal.value = true;
};

const closeEdit = () => {
    showEditModal.value = false;
};

const submit = () => {
    form.full_name = `${form.first_name} ${form.last_name}`.trim();
    form.put(`/clients/${form.uuid}`, {
        preserveScroll: true,
        onSuccess: () => {
            showEditModal.value = false;
        },
    });
};

const documentUrl = (id, type) => `/clients/kyc/${id}/documents/${type}`;

const openDocument = (id, type, label) => {
    selectedDocumentUrl.value = documentUrl(id, type);
    selectedDocumentLabel.value = label;
    showDocumentModal.value = true;
};

const closeDocument = () => {
    showDocumentModal.value = false;
    selectedDocumentUrl.value = '';
    selectedDocumentLabel.value = 'Document';
};

const initials = (name = '') =>
    name
        .split(' ')
        .filter(Boolean)
        .slice(0, 2)
        .map((part) => part[0])
        .join('')
        .toUpperCase();

const statusLabel = (status) => {
    const map = {
        pending: 'Pending',
        verified: 'Verified',
        rejected: 'Rejected',
    };
    return map[status] ?? 'Unknown';
};

const statusClass = (status) => {
    const map = {
        pending: 'bg-amber-50 text-amber-700',
        verified: 'bg-emerald-50 text-emerald-700',
        rejected: 'bg-rose-50 text-rose-700',
    };
    return map[status] ?? 'bg-slate-100 text-slate-600';
};

const cardStatusClass = (status) => {
    const map = {
        generated: 'bg-slate-100 text-slate-600',
        printed: 'bg-amber-100 text-amber-700',
        in_stock: 'bg-sky-100 text-sky-700',
        assigned: 'bg-indigo-100 text-indigo-700',
        created: 'bg-emerald-100 text-emerald-700',
        active: 'bg-emerald-100 text-emerald-700',
    };
    return map[status] ?? 'bg-slate-100 text-slate-600';
};

const formatExpiry = (card) => {
    if (card.expiry_date) {
        return card.expiry_date;
    }
    if (card.expiry_month && card.expiry_year) {
        return `${String(card.expiry_month).padStart(2, '0')}/${card.expiry_year}`;
    }
    return '—';
};
</script>
