<template>
    <div class="space-y-6">
        <Head title="Pre-Generated Cards" />

        <div class="rounded-2xl border border-slate-200 bg-white p-6">
            <div class="flex flex-wrap items-start justify-between gap-4">
                <div>
                    <h3 class="text-lg font-semibold">Pre-Generated Stock</h3>
                    <p class="mt-2 text-xs text-slate-500">
                        Assign stock cards to verified clients once available.
                    </p>
                </div>
            </div>

            <div
                v-if="linkFeedback.message"
                class="mt-4 rounded-lg border px-4 py-3 text-xs"
                :class="linkFeedback.type === 'success'
                    ? 'border-emerald-200 bg-emerald-50 text-emerald-700'
                    : 'border-red-200 bg-red-50 text-red-700'"
            >
                {{ linkFeedback.message }}
            </div>

            <div class="mt-6 flex flex-wrap items-end gap-3 rounded-xl border border-slate-100 bg-slate-50/50 p-4">
                <div>
                    <label class="mb-1 block text-xs font-medium text-slate-600">Status</label>
                    <select
                        v-model="filterForm.status"
                        class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs focus:border-slate-400 focus:outline-none focus:ring-1 focus:ring-slate-400"
                    >
                        <option value="">In stock only</option>
                        <option value="in_stock">In stock</option>
                        <option value="generated">Generated</option>
                        <option value="printed">Printed</option>
                        <option value="assigned">Assigned</option>
                        <option value="active">Active</option>
                        <option value="created">Created</option>
                    </select>
                </div>
                <div>
                    <label class="mb-1 block text-xs font-medium text-slate-600">Institution</label>
                    <select
                        v-model="filterForm.institution_id"
                        class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs focus:border-slate-400 focus:outline-none focus:ring-1 focus:ring-slate-400"
                    >
                        <option value="">All</option>
                        <option
                            v-for="inst in institutions"
                            :key="inst.id"
                            :value="inst.id"
                        >
                            {{ inst.name }}
                        </option>
                    </select>
                </div>
                <div>
                    <label class="mb-1 block text-xs font-medium text-slate-600">Product</label>
                    <select
                        v-model="filterForm.product_id"
                        class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs focus:border-slate-400 focus:outline-none focus:ring-1 focus:ring-slate-400"
                    >
                        <option value="">All</option>
                        <option
                            v-for="prod in filteredProducts"
                            :key="prod.id"
                            :value="prod.id"
                        >
                            {{ prod.name }}
                        </option>
                    </select>
                </div>
                <div>
                    <label class="mb-1 block text-xs font-medium text-slate-600">Batch</label>
                    <select
                        v-model="filterForm.batch_id"
                        class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs focus:border-slate-400 focus:outline-none focus:ring-1 focus:ring-slate-400"
                    >
                        <option value="">All</option>
                        <option
                            v-for="batch in batches"
                            :key="batch.id"
                            :value="batch.id"
                        >
                            {{ batch.label }}
                        </option>
                    </select>
                </div>
                <div>
                    <label class="mb-1 block text-xs font-medium text-slate-600">Search</label>
                    <input
                        v-model="filterForm.search"
                        type="text"
                        placeholder="Card number or UUID"
                        class="rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs focus:border-slate-400 focus:outline-none focus:ring-1 focus:ring-slate-400"
                    />
                </div>
                <button
                    type="button"
                    class="rounded-lg bg-slate-700 px-4 py-2 text-xs font-medium text-white hover:bg-slate-600"
                    @click="applyFilters"
                >
                    Apply
                </button>
            </div>

            <div class="mt-4 overflow-hidden rounded-xl border border-slate-100">
                <table class="w-full 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">Institution</th>
                            <th class="px-4 py-3">Product</th>
                            <th class="px-4 py-3">Expiration Date</th>
                            <th class="px-4 py-3">Status</th>
                            <th class="px-4 py-3 text-right">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr
                            v-for="card in stockCards"
                            :key="card.uuid"
                            class="border-t border-slate-100"
                        >
                            <td class="px-4 py-3 font-medium">
                                {{ card.card_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.expiry_month && card.expiry_year
                                        ? `${String(card.expiry_month).padStart(2, '0')}/${String(card.expiry_year).slice(-2)}`
                                        : '—'
                                }}
                            </td>
                            <td class="px-4 py-3">
                                <span
                                    class="rounded-full bg-amber-100 px-2 py-1 text-[10px] font-semibold text-amber-700"
                                >
                                    {{ card.status }}
                                </span>
                            </td>
                            <td class="px-4 py-3 text-right">
                                <button
                                    type="button"
                                    class="rounded-lg border border-slate-200 px-3 py-1 text-[11px] font-semibold text-slate-700 hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-60"
                                    :disabled="!canAssign || assignForm.processing"
                                    @click="openAssignModal(card)"
                                >
                                    Assign Card
                                </button>
                            </td>
                        </tr>
                        <tr v-if="stockCards.length === 0">
                            <td
                                class="px-4 py-6 text-center text-xs text-slate-400"
                                colspan="6"
                            >
                                No stock cards available.
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div
                v-if="pagination && pagination.last_page > 1"
                class="mt-4 flex flex-wrap items-center justify-between gap-3 border-t border-slate-100 pt-4"
            >
                <p class="text-xs text-slate-500">
                    Showing {{ pagination.from ?? 0 }}–{{ pagination.to ?? 0 }} of {{ pagination.total }}
                </p>
                <div class="flex items-center gap-1">
                    <a
                        v-if="pagination.prev_page_url"
                        :href="pagination.prev_page_url"
                        class="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50"
                        @click.prevent="goToUrl(pagination.prev_page_url)"
                    >
                        Previous
                    </a>
                    <template v-for="(link, i) in pagination.links" :key="i">
                        <span
                            v-if="link.label === '...'"
                            class="px-2 py-1 text-xs text-slate-400"
                        >
                            {{ link.label }}
                        </span>
                        <a
                            v-else-if="link.url"
                            :href="link.url"
                            class="rounded-lg border px-3 py-1.5 text-xs font-medium"
                            :class="link.active ? 'border-slate-700 bg-slate-700 text-white' : 'border-slate-200 text-slate-700 hover:bg-slate-50'"
                            @click.prevent="goToUrl(link.url)"
                        >
                            {{ link.label || link.page }}
                        </a>
                    </template>
                    <a
                        v-if="pagination.next_page_url"
                        :href="pagination.next_page_url"
                        class="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-700 hover:bg-slate-50"
                        @click.prevent="goToUrl(pagination.next_page_url)"
                    >
                        Next
                    </a>
                </div>
            </div>
        </div>

        <div
            v-if="assignModal.open"
            class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 px-4"
        >
            <div class="w-full max-w-2xl rounded-2xl border border-slate-200 bg-white p-5 shadow-xl">
                <div class="flex items-start justify-between gap-3">
                    <div>
                        <h4 class="text-base font-semibold text-slate-800">Assign Card</h4>
                        <p class="mt-1 text-xs text-slate-500">
                            Select a client to link with card {{ assignModal.card?.card_number || '—' }}.
                        </p>
                    </div>
                    <button
                        type="button"
                        class="rounded-lg px-2 py-1 text-xs text-slate-500 hover:bg-slate-100"
                        @click="closeAssignModal"
                    >
                        Close
                    </button>
                </div>

                <div class="mt-4 flex flex-wrap items-end gap-2">
                    <div class="min-w-0 flex-1">
                        <label class="mb-1 block text-xs font-medium text-slate-600">Client search</label>
                        <input
                            v-model="assignModal.search"
                            type="text"
                            placeholder="Name, client code, or UUID"
                            class="w-full rounded-lg border border-slate-200 px-3 py-2 text-xs focus:border-slate-400 focus:outline-none focus:ring-1 focus:ring-slate-400"
                            @keyup.enter="searchClients"
                        />
                    </div>
                    <button
                        type="button"
                        class="rounded-lg bg-slate-700 px-4 py-2 text-xs font-medium text-white hover:bg-slate-600 disabled:cursor-not-allowed disabled:opacity-60"
                        :disabled="assignModal.loading"
                        @click="searchClients"
                    >
                        {{ assignModal.loading ? 'Searching...' : 'Search' }}
                    </button>
                </div>

                <p
                    v-if="assignModal.error"
                    class="mt-2 text-[11px] text-red-600"
                >
                    {{ assignModal.error }}
                </p>

                <div class="mt-4 max-h-72 overflow-y-auto rounded-xl border border-slate-100">
                    <div
                        v-if="!assignModal.hasSearched"
                        class="px-4 py-6 text-center text-xs text-slate-400"
                    >
                        Search to find a client.
                    </div>
                    <div
                        v-else-if="assignModal.results.length === 0"
                        class="px-4 py-6 text-center text-xs text-slate-400"
                    >
                        No matching clients found.
                    </div>
                    <label
                        v-for="client in assignModal.results"
                        :key="client.uuid"
                        class="flex cursor-pointer items-start gap-3 border-t border-slate-100 px-4 py-3 first:border-t-0 hover:bg-slate-50"
                    >
                        <input
                            v-model="assignModal.client_uuid"
                            type="radio"
                            name="selected-client"
                            :value="client.uuid"
                            class="mt-0.5"
                        />
                        <span class="min-w-0">
                            <span class="block truncate text-xs font-semibold text-slate-700">
                                {{ client.full_name }}
                            </span>
                            <span class="block truncate text-[11px] text-slate-500">
                                {{ client.client_code }} • {{ client.uuid }}
                            </span>
                        </span>
                    </label>
                </div>

                <p
                    v-if="assignForm.errors.client_uuid"
                    class="mt-2 text-[11px] text-red-600"
                >
                    {{ assignForm.errors.client_uuid }}
                </p>
                <p
                    v-if="assignForm.errors.card_uuid"
                    class="mt-2 text-[11px] text-red-600"
                >
                    {{ assignForm.errors.card_uuid }}
                </p>

                <div class="mt-5 flex items-center justify-end gap-2">
                    <button
                        type="button"
                        class="rounded-lg border border-slate-200 px-4 py-2 text-xs font-medium text-slate-700 hover:bg-slate-50"
                        @click="closeAssignModal"
                    >
                        Cancel
                    </button>
                    <button
                        type="button"
                        class="rounded-lg bg-slate-700 px-4 py-2 text-xs font-medium text-white hover:bg-slate-600 disabled:cursor-not-allowed disabled:opacity-60"
                        :disabled="!assignModal.client_uuid || assignForm.processing"
                        @click="linkSelectedCard"
                    >
                        {{ assignForm.processing ? 'Linking...' : 'Link Card' }}
                    </button>
                </div>
            </div>
        </div>
    </div>
</template>

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

defineOptions({
    layout: (h, page) =>
        h(AuthenticatedLayout, { title: 'Pre-Generated Cards' }, () => page),
});

const props = defineProps({
    stockCards: {
        type: Array,
        default: () => [],
    },
    batches: {
        type: Array,
        default: () => [],
    },
    institutions: {
        type: Array,
        default: () => [],
    },
    products: {
        type: Array,
        default: () => [],
    },
    canAssign: {
        type: Boolean,
        default: false,
    },
    filters: {
        type: Object,
        default: () => ({}),
    },
    pagination: {
        type: Object,
        default: () => null,
    },
});

const filterForm = reactive({
    status: props.filters?.status ?? '',
    institution_id: props.filters?.institution_id ?? '',
    product_id: props.filters?.product_id ?? '',
    batch_id: props.filters?.batch_id ?? '',
    search: props.filters?.search ?? '',
});

watch(
    () => props.filters,
    (f) => {
        if (f) {
            filterForm.status = f.status ?? '';
            filterForm.institution_id = f.institution_id ?? '';
            filterForm.product_id = f.product_id ?? '';
            filterForm.batch_id = f.batch_id ?? '';
            filterForm.search = f.search ?? '';
        }
    },
    { immediate: true }
);

const filteredProducts = computed(() => {
    if (!filterForm.institution_id) return props.products;
    return props.products.filter(
        (p) => String(p.institution_id) === String(filterForm.institution_id)
    );
});

function applyFilters() {
    const params = {
        page: 1,
        status: filterForm.status || undefined,
        institution_id: filterForm.institution_id || undefined,
        product_id: filterForm.product_id || undefined,
        batch_id: filterForm.batch_id || undefined,
        search: filterForm.search?.trim() || undefined,
    };
    router.get('/cards/pre-generated', params);
}

function goToUrl(url) {
    if (!url) return;
    router.visit(url);
}

const assignForm = useForm({
    client_uuid: '',
});

const assignModal = reactive({
    open: false,
    card: null,
    search: '',
    loading: false,
    hasSearched: false,
    results: [],
    error: '',
    client_uuid: '',
});

const linkFeedback = reactive({
    type: '',
    message: '',
});

function openAssignModal(card) {
    if (!props.canAssign) return;

    linkFeedback.type = '';
    linkFeedback.message = '';
    assignModal.open = true;
    assignModal.card = card;
    assignModal.search = '';
    assignModal.loading = false;
    assignModal.hasSearched = false;
    assignModal.results = [];
    assignModal.error = '';
    assignModal.client_uuid = '';
    assignForm.clearErrors();
}

function closeAssignModal() {
    assignModal.open = false;
    assignModal.card = null;
    assignModal.search = '';
    assignModal.loading = false;
    assignModal.hasSearched = false;
    assignModal.results = [];
    assignModal.error = '';
    assignModal.client_uuid = '';
    assignForm.reset();
    assignForm.clearErrors();
}

async function searchClients() {
    assignModal.error = '';
    assignModal.hasSearched = true;
    assignModal.client_uuid = '';
    assignForm.clearErrors();

    const term = assignModal.search.trim();
    if (!term) {
        assignModal.results = [];
        return;
    }

    assignModal.loading = true;

    try {
        const response = await window.axios.get('/cards/pre-generated/client-search', {
            params: {
                search: term,
            },
        });
        assignModal.results = response.data?.clients ?? [];
    } catch (error) {
        assignModal.results = [];
        assignModal.error = error?.response?.data?.message ?? 'Unable to search clients right now.';
    } finally {
        assignModal.loading = false;
    }
}

function linkSelectedCard() {
    if (!assignModal.card || !assignModal.client_uuid) return;

    const selectedClient = assignModal.results.find(
        (client) => client.uuid === assignModal.client_uuid
    );

    const confirmMessage = selectedClient
        ? `Link card ${assignModal.card.card_number || assignModal.card.uuid} to ${selectedClient.full_name} (${selectedClient.client_code})?`
        : `Link card ${assignModal.card.card_number || assignModal.card.uuid} to the selected client?`;

    if (!window.confirm(confirmMessage)) {
        return;
    }

    linkFeedback.type = '';
    linkFeedback.message = '';
    assignForm.client_uuid = assignModal.client_uuid;
    assignForm.put(`/cards/${assignModal.card.uuid}/assign`, {
        preserveScroll: true,
        onSuccess: () => {
            linkFeedback.type = 'success';
            linkFeedback.message = 'Card linked successfully.';
            closeAssignModal();
        },
        onError: (errors) => {
            linkFeedback.type = 'error';
            linkFeedback.message = errors?.card_uuid || errors?.client_uuid || 'Failed to link card.';
        },
    });
}
</script>
