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

const props = defineProps({
    requests: Object,
    filters: Object,
    payoutStatuses: Array,
    payoutSettings: {
        type: Object,
        default: () => ({ mode: 'manual' }),
    },
});

const query = reactive({ payout_status: props.filters?.payout_status || 'pending' });
const paidForm = useForm({ action: 'mark_paid', payout_reference: '', admin_note: '' });
const failedForm = useForm({ action: 'mark_failed', payout_failure_reason: '', admin_note: '' });
const smeplugForm = useForm({ action: 'send_smeplug', admin_note: '' });

const applyFilters = () => {
    router.get(route('admin.airtime-to-cash.payout-queue'), query, { preserveState: true, replace: true });
};

const markPaid = (id) => {
    const payoutReference = window.prompt('Enter payout reference for this bank transfer:');
    if (!payoutReference || !String(payoutReference).trim()) return;

    paidForm.payout_reference = String(payoutReference).trim();
    paidForm.post(route('admin.airtime-to-cash.payout.update', id), {
        preserveScroll: true,
        onFinish: () => paidForm.reset('payout_reference', 'admin_note'),
    });
};

const markFailed = (id) => {
    const reason = window.prompt('Enter failure reason:');
    if (!reason || !String(reason).trim()) return;

    failedForm.payout_failure_reason = String(reason).trim();
    failedForm.post(route('admin.airtime-to-cash.payout.update', id), {
        preserveScroll: true,
        onFinish: () => failedForm.reset('payout_failure_reason', 'admin_note'),
    });
};

const sendViaSmeplug = (id) => {
    if (!window.confirm('Send this bank payout via SMEPlug now?')) return;

    smeplugForm.post(route('admin.airtime-to-cash.payout.update', id), {
        preserveScroll: true,
        onFinish: () => smeplugForm.reset('admin_note'),
    });
};
</script>

<template>
    <Head title="A2C Payout Queue" />

    <AdminLayout>
        <template #header>
            <div>
                <h2 class="text-xl font-semibold text-gray-800">A2C Bank Payout Queue</h2>
                <p class="mt-1 text-sm text-gray-500">Process approved bank payouts and track payout references.</p>
            </div>
        </template>

        <div class="mx-auto max-w-7xl space-y-6 px-4 py-6 sm:px-6 lg:px-8">
            <AppCard title="Payout Integration">
                <div class="rounded-lg border border-indigo-200 bg-indigo-50 p-3 text-sm text-indigo-900">
                    <div>
                        Mode:
                        <span class="font-semibold uppercase">{{ payoutSettings?.mode || 'manual' }}</span>
                    </div>
                    <div v-if="(payoutSettings?.mode || 'manual') === 'smeplug'" class="mt-1 text-xs">
                        Vendor:
                        <span class="font-semibold">{{ payoutSettings?.smeplug_vendor_name || 'Not selected' }}</span>
                        <span v-if="!payoutSettings?.smeplug_vendor_active" class="ml-1 text-rose-700">(inactive)</span>
                    </div>
                    <div v-if="(payoutSettings?.mode || 'manual') !== 'smeplug'" class="mt-1 text-xs">
                        SMEPlug payout is currently off. Switch mode in Commerce Settings.
                    </div>
                </div>
            </AppCard>

            <AppCard title="Queue Filter">
                <div class="flex gap-2">
                    <select v-model="query.payout_status" class="rounded-md border-gray-300 text-sm shadow-sm">
                        <option value="">All payout statuses</option>
                        <option v-for="status in payoutStatuses" :key="status" :value="status">{{ status }}</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="Bank Payout Requests">
                <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">Bank Details</th>
                            <th class="px-4 py-3">Amount</th>
                            <th class="px-4 py-3">Request Status</th>
                            <th class="px-4 py-3">Payout Status</th>
                            <th class="px-4 py-3">Payout Ref</th>
                            <th class="px-4 py-3">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100 text-sm">
                        <tr v-for="item in requests.data" :key="item.id">
                            <td class="px-4 py-3">
                                <div class="font-medium text-gray-900">{{ item.user?.name }}</div>
                                <div class="text-xs text-gray-500">{{ item.user?.email }}</div>
                                <div class="text-xs text-gray-500 mt-1">{{ item.reference }}</div>
                            </td>
                            <td class="px-4 py-3 text-xs text-gray-700">
                                <div class="font-semibold text-gray-800">{{ item.bank_name || '-' }}</div>
                                <div v-if="item.bank_code">Code: {{ item.bank_code }}</div>
                                <div>{{ item.bank_account_number || '-' }}</div>
                                <div>{{ item.bank_account_name || '-' }}</div>
                            </td>
                            <td class="px-4 py-3">
                                <div>NGN {{ item.payout_amount }}</div>
                                <div class="text-xs text-gray-500">From NGN {{ item.airtime_amount }} ({{ item.rate_percent }}%)</div>
                            </td>
                            <td class="px-4 py-3"><StatusBadge :status="item.status" /></td>
                            <td class="px-4 py-3"><StatusBadge :status="item.payout_status || 'pending'" /></td>
                            <td class="px-4 py-3 text-xs text-gray-600">
                                <div class="font-mono">{{ item.payout_reference || '-' }}</div>
                                <div v-if="item.payout_paid_at" class="mt-1">Paid: {{ item.payout_paid_at }}</div>
                                <div v-if="item.payout_failure_reason" class="mt-1 text-rose-600">{{ item.payout_failure_reason }}</div>
                            </td>
                            <td class="px-4 py-3">
                                <div class="flex gap-2" v-if="item.status === 'approved'">
                                    <button
                                        v-if="(payoutSettings?.mode || 'manual') === 'smeplug'"
                                        type="button"
                                        class="rounded border border-indigo-300 bg-indigo-50 px-2.5 py-1 text-xs text-indigo-700"
                                        :disabled="item.payout_status === 'paid' || paidForm.processing || failedForm.processing || smeplugForm.processing || !payoutSettings?.smeplug_vendor_active"
                                        @click="sendViaSmeplug(item.id)"
                                    >
                                        Send via SMEPlug
                                    </button>
                                    <button
                                        type="button"
                                        class="rounded border border-emerald-300 bg-emerald-50 px-2.5 py-1 text-xs text-emerald-700"
                                        :disabled="item.payout_status === 'paid' || paidForm.processing || failedForm.processing || smeplugForm.processing"
                                        @click="markPaid(item.id)"
                                    >
                                        Mark Paid
                                    </button>
                                    <button
                                        type="button"
                                        class="rounded border border-rose-300 bg-rose-50 px-2.5 py-1 text-xs text-rose-700"
                                        :disabled="paidForm.processing || failedForm.processing || smeplugForm.processing"
                                        @click="markFailed(item.id)"
                                    >
                                        Mark Failed
                                    </button>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </AppTable>
            </AppCard>
        </div>
    </AdminLayout>
</template>
