<script setup>
import { computed, ref } from 'vue';
import { Head, Link, usePage } from '@inertiajs/vue3';
import QuickMenuGrid from '@/Components/app/QuickMenuGrid.vue';
import AppCard from '@/Components/ui/AppCard.vue';
import MobileAppLayout from '@/Layouts/MobileAppLayout.vue';
import StatusBadge from '@/Components/ui/StatusBadge.vue';
import TransactionReceiptModal from '@/Components/app/TransactionReceiptModal.vue';

const props = defineProps({
    walletBalance: [String, Number],
    reservedAccounts: {
        type: Array,
        default: () => [],
    },
    fundingMethods: {
        type: Object,
        default: () => ({}),
    },
    recentTransactions: Array,
});

const page = usePage();
const appName = computed(() => String(page.props?.branding?.app_name || 'VTU App').trim());

const copiedAccountKey = ref('');
const showReceiptModal = ref(false);
const selectedReceipt = ref(null);
const showReservedFunding = computed(() => {
    return !!props.fundingMethods?.monnify_reserved?.available
        || !!props.fundingMethods?.paymentpoint_reserved?.available;
});

const normalizeProviderLabel = (value) => {
    const raw = String(value || '').trim();
    if (!raw) return 'Provider';

    const cleaned = raw.replace(/\bbank\b/gi, '').replace(/\s{2,}/g, ' ').trim();

    return cleaned || 'Provider';
};

const fundingAccounts = computed(() => {
    return (props.reservedAccounts || []).flatMap((record) => {
        const entries = normalizeEntries(record?.accounts_json);

        return entries.map((entry, index) => ({
            key: `${record.id}-${index}`,
            bankName: normalizeProviderLabel(entry?.bankName || entry?.bank_name || entry?.bank || ''),
            accountNumber: String(entry?.accountNumber || entry?.account_number || ''),
            accountReference: String(record?.account_reference || ''),
        }));
    }).slice(0, 4);
});

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

    try {
        if (navigator?.clipboard?.writeText) {
            await navigator.clipboard.writeText(text);
        } else {
            fallbackCopy(text);
        }
    } catch {
        fallbackCopy(text);
    }

    copiedAccountKey.value = key;
    window.setTimeout(() => {
        if (copiedAccountKey.value === key) {
            copiedAccountKey.value = '';
        }
    }, 1200);
};

const fallbackCopy = (text) => {
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.setAttribute('readonly', '');
    textarea.style.position = 'absolute';
    textarea.style.left = '-9999px';
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
};

const normalizeEntries = (raw) => {
    const value = parseMaybeJson(raw);

    if (Array.isArray(value)) {
        return value;
    }

    if (value && typeof value === 'object') {
        if (Array.isArray(value.accounts)) return value.accounts;

        const hasShape = value?.accountNumber || value?.account_number || value?.bankName || value?.bank_name;
        if (hasShape) return [value];
    }

    return [];
};

const parseMaybeJson = (value) => {
    if (typeof value !== 'string') return value;

    try {
        return JSON.parse(value);
    } catch {
        return value;
    }
};

const openReceipt = (transaction) => {
    selectedReceipt.value = transaction?.receipt || null;
    showReceiptModal.value = true;
};

const closeReceiptModal = () => {
    showReceiptModal.value = false;
};
</script>

<template>
    <Head title="App Dashboard" />

    <MobileAppLayout title="Dashboard" :subtitle="`Your ${appName} home`">
        <div class="space-y-4">
            <section class="user-balance-card user-balance-card--dashboard rounded-3xl p-4 shadow-lg">
                <div class="flex items-start justify-between gap-3">
                    <div>
                        <div class="text-xs uppercase tracking-[0.16em] user-balance-card__kicker">Available Balance</div>
                        <div class="mt-2 text-2xl font-semibold">NGN {{ walletBalance }}</div>
                        <div class="mt-1 text-xs user-balance-card__muted">{{ appName }} service credit for purchases.</div>
                    </div>
                    <Link
                        :href="route('app.wallet')"
                        class="user-balance-card__chip rounded-full border px-3 py-1.5 text-xs font-medium backdrop-blur"
                    >
                        Wallet
                    </Link>
                </div>

                <div class="mt-4 grid grid-cols-2 gap-2 min-[360px]:grid-cols-3">
                    <Link
                        :href="route('app.buy.data')"
                        class="user-balance-card__action rounded-xl border px-3 py-2 text-center text-xs font-medium ring-1 transition"
                    >
                        Buy Data
                    </Link>
                    <Link
                        :href="route('app.buy.airtime')"
                        class="user-balance-card__action rounded-xl border px-3 py-2 text-center text-xs font-medium ring-1 transition"
                    >
                        Airtime
                    </Link>
                    <Link
                        :href="route('app.support.tickets.create')"
                        class="user-balance-card__action rounded-xl border px-3 py-2 text-center text-xs font-medium ring-1 transition"
                    >
                        More
                    </Link>
                </div>

                <div v-if="showReservedFunding" class="mt-3 space-y-1.5">
                    <div class="text-[10px] font-semibold uppercase tracking-[0.14em] user-balance-card__muted">
                        Funding Accounts
                    </div>

                    <div
                        v-if="!fundingAccounts.length"
                        class="user-balance-card__action rounded-xl px-2.5 py-2 text-[11px] ring-1"
                    >
                        No funding account yet.
                        <Link :href="route('app.wallet')" class="ml-1 font-semibold underline underline-offset-2">
                            Open Wallet
                        </Link>
                    </div>

                    <div v-if="fundingAccounts.length" class="grid grid-cols-2 gap-2">
                        <div
                            v-for="item in fundingAccounts"
                            :key="item.key"
                            class="user-balance-card__action grid grid-cols-[1fr_auto] items-center gap-1.5 rounded-xl px-2 py-2 ring-1"
                        >
                            <div class="min-w-0">
                                <div class="truncate text-[10px] uppercase tracking-[0.08em] user-balance-card__muted">{{ item.bankName }}</div>
                                <div class="truncate text-sm font-semibold tracking-[0.02em]">{{ item.accountNumber || '-' }}</div>
                            </div>
                            <button
                                type="button"
                                class="user-balance-card__chip inline-flex h-6 w-6 items-center justify-center rounded-md border text-[11px] font-semibold disabled:cursor-not-allowed disabled:opacity-50"
                                :disabled="!item.accountNumber"
                                @click="copyAccountNumber(item.accountNumber, item.key)"
                            >
                                {{ copiedAccountKey === item.key ? '✓' : '⎘' }}
                            </button>
                        </div>
                    </div>

                    <div v-if="fundingAccounts.length" class="text-right">
                        <Link :href="route('app.wallet')" class="text-[11px] font-semibold user-balance-card__muted underline decoration-dotted underline-offset-2">
                            View all accounts
                        </Link>
                    </div>
                </div>
            </section>

            <AppCard title="Quick Menu">
                <QuickMenuGrid />
            </AppCard>

            <AppCard title="Recent Transactions">
                <div class="space-y-2">
                    <button
                        v-for="transaction in recentTransactions"
                        :key="transaction.id"
                        type="button"
                        class="w-full rounded-2xl border border-slate-200 bg-white p-3 text-left transition hover:border-slate-300"
                        @click="openReceipt(transaction)"
                    >
                        <div class="flex items-start justify-between gap-3">
                            <div class="min-w-0">
                                <div class="truncate text-sm font-semibold text-slate-900">{{ transaction.category?.name }}</div>
                                <div class="truncate text-xs text-slate-500">
                                    {{ transaction.plan?.name || transaction.internal_reference }}
                                </div>
                            </div>
                            <StatusBadge :status="transaction.status" />
                        </div>
                        <div class="mt-2 flex items-center justify-between text-xs">
                            <span class="truncate text-slate-500">{{ transaction.internal_reference }}</span>
                            <span class="font-semibold text-slate-800">NGN {{ transaction.amount_charged }}</span>
                        </div>
                    </button>
                    <div v-if="recentTransactions.length === 0" class="rounded-2xl border border-dashed border-slate-300 p-4 text-sm text-slate-500">
                        No transactions yet.
                    </div>
                </div>
            </AppCard>
        </div>

        <TransactionReceiptModal
            :show="showReceiptModal"
            :receipt="selectedReceipt"
            @close="closeReceiptModal"
        />
    </MobileAppLayout>
</template>
