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

const props = defineProps({
    summary: {
        type: Object,
        default: () => ({}),
    },
    serviceSummary: {
        type: Array,
        default: () => [],
    },
    categorySummary: {
        type: Array,
        default: () => [],
    },
    vendorPerformance: {
        type: Array,
        default: () => [],
    },
    timeline: {
        type: Array,
        default: () => [],
    },
    reliability: {
        type: Object,
        default: () => ({}),
    },
    filters: {
        type: Object,
        default: () => ({}),
    },
});

const tabs = [
    { key: 'overview', label: 'Overview' },
    { key: 'services', label: 'Service Summary' },
    { key: 'vendors', label: 'Vendor Performance' },
    { key: 'reliability', label: 'Reliability' },
];

const activeTab = ref(props.filters?.tab || 'overview');

const query = reactive({
    range: props.filters?.range || 'today',
    group_by: props.filters?.group_by || 'day',
    start_date: props.filters?.start_date || '',
    end_date: props.filters?.end_date || '',
});

const applyFilters = () => {
    router.get(route('admin.reports.index'), {
        ...query,
        tab: activeTab.value,
    }, {
        preserveState: true,
        preserveScroll: true,
        replace: true,
    });
};

const setRange = (range) => {
    query.range = range;
    if (range !== 'custom') {
        applyFilters();
    }
};

const setGroupBy = (groupBy) => {
    query.group_by = groupBy;
    applyFilters();
};

const setTab = (tab) => {
    activeTab.value = tab;
};

const formatMoney = (value) => {
    const n = Number(value ?? 0);
    if (Number.isNaN(n)) return 'NGN 0.00';
    return `NGN ${n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};

const formatNumber = (value) => {
    const n = Number(value ?? 0);
    if (Number.isNaN(n)) return '0';
    return n.toLocaleString();
};

const timelineMax = computed(() => {
    const values = (props.timeline || []).flatMap((row) => [Number(row.gross_sales || 0), Number(row.realized_profit || row.total_profit || 0)]);
    return Math.max(...values, 1);
});
</script>

<template>
    <Head title="Reports" />
    <AdminLayout>
        <template #header>
            <div class="flex flex-wrap items-center justify-between gap-4">
                <div>
                    <h2 class="text-xl font-semibold text-gray-800">Reports</h2>
                    <p class="mt-1 text-sm text-gray-500">Accurate date-range analytics for sales, profit, service mix, and transaction reliability.</p>
                </div>
                <div class="flex items-center gap-2">
                    <Link
                        :href="route('admin.reports.export-csv', { ...query, tab: activeTab })"
                        class="rounded-md border border-gray-300 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
                    >
                        Export CSV
                    </Link>
                    <Link
                        :href="route('admin.dashboard')"
                        class="rounded-md border border-gray-300 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
                    >
                        Dashboard
                    </Link>
                    <Link
                        :href="route('admin.transactions.index')"
                        class="rounded-md border border-gray-300 px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50"
                    >
                        Transactions
                    </Link>
                </div>
            </div>
        </template>

        <div class="mx-auto max-w-7xl space-y-6 px-4 py-6 sm:px-6 lg:px-8">
            <AppCard title="Report Filters" subtitle="Use daily/weekly grouping with quick ranges or custom dates.">
                <div class="flex flex-wrap items-center gap-2">
                    <button type="button" class="rounded-md px-3 py-1.5 text-xs font-semibold" :class="query.range === 'today' ? 'bg-slate-900 text-white' : 'border border-slate-300 bg-white text-slate-700'" @click="setRange('today')">Today</button>
                    <button type="button" class="rounded-md px-3 py-1.5 text-xs font-semibold" :class="query.range === '7d' ? 'bg-slate-900 text-white' : 'border border-slate-300 bg-white text-slate-700'" @click="setRange('7d')">7D</button>
                    <button type="button" class="rounded-md px-3 py-1.5 text-xs font-semibold" :class="query.range === '30d' ? 'bg-slate-900 text-white' : 'border border-slate-300 bg-white text-slate-700'" @click="setRange('30d')">30D</button>
                    <button type="button" class="rounded-md px-3 py-1.5 text-xs font-semibold" :class="query.range === 'this_week' ? 'bg-slate-900 text-white' : 'border border-slate-300 bg-white text-slate-700'" @click="setRange('this_week')">This Week</button>
                    <button type="button" class="rounded-md px-3 py-1.5 text-xs font-semibold" :class="query.range === 'this_month' ? 'bg-slate-900 text-white' : 'border border-slate-300 bg-white text-slate-700'" @click="setRange('this_month')">This Month</button>
                    <button type="button" class="rounded-md px-3 py-1.5 text-xs font-semibold" :class="query.range === 'custom' ? 'bg-slate-900 text-white' : 'border border-slate-300 bg-white text-slate-700'" @click="setRange('custom')">Custom</button>

                    <div class="ml-auto flex items-center gap-2">
                        <button type="button" class="rounded-md px-3 py-1.5 text-xs font-semibold" :class="query.group_by === 'day' ? 'bg-emerald-600 text-white' : 'border border-slate-300 bg-white text-slate-700'" @click="setGroupBy('day')">Daily</button>
                        <button type="button" class="rounded-md px-3 py-1.5 text-xs font-semibold" :class="query.group_by === 'week' ? 'bg-emerald-600 text-white' : 'border border-slate-300 bg-white text-slate-700'" @click="setGroupBy('week')">Weekly</button>
                    </div>
                </div>

                <div v-if="query.range === 'custom'" class="mt-3 grid gap-3 sm:grid-cols-4">
                    <input v-model="query.start_date" type="date" class="rounded-md border-slate-300 text-xs shadow-sm" />
                    <input v-model="query.end_date" type="date" class="rounded-md border-slate-300 text-xs shadow-sm" />
                    <button type="button" class="rounded-md border border-slate-300 bg-white px-3 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-50" @click="applyFilters">Apply Custom Range</button>
                </div>
            </AppCard>

            <div class="inline-flex rounded-lg border border-slate-200 bg-white p-1">
                <button
                    v-for="item in tabs"
                    :key="item.key"
                    type="button"
                    class="rounded-md px-3 py-1.5 text-xs font-semibold"
                    :class="activeTab === item.key ? 'bg-slate-900 text-white' : 'text-slate-600 hover:bg-slate-100'"
                    @click="setTab(item.key)"
                >
                    {{ item.label }}
                </button>
            </div>

            <div v-if="activeTab === 'overview'" class="space-y-6">
                <div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
                    <AppCard title="Transactions" :subtitle="formatNumber(summary.total_transactions)" />
                    <AppCard title="Gross Sales" :subtitle="formatMoney(summary.gross_sales)" />
                    <AppCard title="Vendor Cost" :subtitle="formatMoney(summary.vendor_cost_total)" />
                    <AppCard title="Realized Profit" :subtitle="formatMoney(summary.realized_profit)" />
                    <AppCard title="Failure Impact" :subtitle="formatMoney(summary.failure_impact)" />
                    <AppCard title="Net Profit" :subtitle="formatMoney(summary.net_profit)" />
                    <AppCard title="Success Rate" :subtitle="`${summary.success_rate || 0}%`" />
                    <AppCard title="Avg Order Value" :subtitle="formatMoney(summary.avg_order_value)" />
                    <AppCard title="Pending / Stuck" :subtitle="`${summary.pending_count || 0} / ${summary.stuck_count || 0}`" />
                    <AppCard title="Failed" :subtitle="formatNumber(summary.failed_count)" />
                </div>

                <div class="grid gap-6 xl:grid-cols-2">
                    <AppCard title="Timeline" :subtitle="query.group_by === 'week' ? 'Weekly sales and realized-profit trend.' : 'Daily sales and realized-profit trend.'">
                        <div class="space-y-2">
                            <div v-for="row in timeline" :key="row.period_start" class="rounded-lg border border-slate-200 p-3">
                                <div class="flex items-center justify-between text-xs text-slate-600">
                                    <span>{{ row.label }}</span>
                                    <span>{{ row.total_transactions }} txns</span>
                                </div>
                                <div class="mt-2 h-2 rounded bg-slate-100">
                                    <div class="h-2 rounded bg-slate-800" :style="{ width: `${Math.max(2, Math.round((Number(row.gross_sales || 0) / timelineMax) * 100))}%` }" />
                                </div>
                                <div class="mt-2 flex items-center justify-between text-xs">
                                    <span class="text-slate-700">Gross: {{ formatMoney(row.gross_sales) }}</span>
                                    <span class="text-emerald-700">Realized: {{ formatMoney(row.realized_profit || row.total_profit) }}</span>
                                </div>
                                <div class="mt-1 flex items-center justify-between text-xs">
                                    <span class="text-rose-700">Failure Impact: {{ formatMoney(row.failure_impact) }}</span>
                                    <span class="text-slate-700">Net: {{ formatMoney(row.net_profit) }}</span>
                                </div>
                            </div>
                            <div v-if="!timeline.length" class="rounded border border-dashed border-slate-300 px-3 py-4 text-xs text-slate-500">
                                No timeline data for selected range.
                            </div>
                        </div>
                    </AppCard>

                    <AppCard title="Status Mix" subtitle="Execution status breakdown for selected range.">
                        <div class="space-y-2 text-sm">
                            <div class="flex items-center justify-between rounded-md border border-slate-200 px-3 py-2">
                                <span>Success</span>
                                <span class="font-semibold text-emerald-700">{{ formatNumber(summary.success_count) }}</span>
                            </div>
                            <div class="flex items-center justify-between rounded-md border border-slate-200 px-3 py-2">
                                <span>Pending</span>
                                <span class="font-semibold text-amber-700">{{ formatNumber(summary.pending_count) }}</span>
                            </div>
                            <div class="flex items-center justify-between rounded-md border border-slate-200 px-3 py-2">
                                <span>Failed / Reversed</span>
                                <span class="font-semibold text-rose-700">{{ formatNumber(summary.failed_count) }}</span>
                            </div>
                            <div class="flex items-center justify-between rounded-md border border-slate-200 px-3 py-2">
                                <span>Stuck</span>
                                <span class="font-semibold text-slate-800">{{ formatNumber(summary.stuck_count) }}</span>
                            </div>
                            <div class="mt-3 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-xs text-slate-600">
                                Realized Margin: {{ summary.profit_margin_percent || 0 }}% | Net Margin: {{ summary.net_margin_percent || 0 }}%
                            </div>
                        </div>
                    </AppCard>
                </div>
            </div>

            <div v-if="activeTab === 'services'" class="space-y-6">
                <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">Service</th>
                            <th class="px-4 py-3">Transactions</th>
                            <th class="px-4 py-3">Success Rate</th>
                            <th class="px-4 py-3">Gross</th>
                            <th class="px-4 py-3">Realized</th>
                            <th class="px-4 py-3">Failure Impact</th>
                            <th class="px-4 py-3">Net</th>
                            <th class="px-4 py-3">Pending</th>
                            <th class="px-4 py-3">Failed</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100 text-sm">
                        <tr v-for="row in serviceSummary" :key="row.service_key">
                            <td class="px-4 py-3 font-medium text-gray-900">{{ row.label }}</td>
                            <td class="px-4 py-3">{{ formatNumber(row.total_transactions) }}</td>
                            <td class="px-4 py-3">{{ row.success_rate }}%</td>
                            <td class="px-4 py-3">{{ formatMoney(row.gross_sales) }}</td>
                            <td class="px-4 py-3">{{ formatMoney(row.realized_profit || row.total_profit) }}</td>
                            <td class="px-4 py-3">{{ formatMoney(row.failure_impact) }}</td>
                            <td class="px-4 py-3">{{ formatMoney(row.net_profit) }}</td>
                            <td class="px-4 py-3">{{ formatNumber(row.pending_count) }}</td>
                            <td class="px-4 py-3">{{ formatNumber(row.failed_count) }}</td>
                        </tr>
                        <tr v-if="!serviceSummary.length">
                            <td colspan="9" class="px-4 py-4 text-center text-xs text-gray-500">No service summary for selected range.</td>
                        </tr>
                    </tbody>
                </AppTable>

                <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">Category</th>
                            <th class="px-4 py-3">Slug</th>
                            <th class="px-4 py-3">Transactions</th>
                            <th class="px-4 py-3">Gross</th>
                            <th class="px-4 py-3">Realized</th>
                            <th class="px-4 py-3">Failure Impact</th>
                            <th class="px-4 py-3">Net</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100 text-sm">
                        <tr v-for="row in categorySummary" :key="row.category_slug + row.category_name">
                            <td class="px-4 py-3 font-medium text-gray-900">{{ row.category_name }}</td>
                            <td class="px-4 py-3 text-gray-500">{{ row.category_slug }}</td>
                            <td class="px-4 py-3">{{ formatNumber(row.total_transactions) }}</td>
                            <td class="px-4 py-3">{{ formatMoney(row.gross_sales) }}</td>
                            <td class="px-4 py-3">{{ formatMoney(row.realized_profit || row.total_profit) }}</td>
                            <td class="px-4 py-3">{{ formatMoney(row.failure_impact) }}</td>
                            <td class="px-4 py-3">{{ formatMoney(row.net_profit) }}</td>
                        </tr>
                        <tr v-if="!categorySummary.length">
                            <td colspan="7" class="px-4 py-4 text-center text-xs text-gray-500">No category summary for selected range.</td>
                        </tr>
                    </tbody>
                </AppTable>
            </div>

            <div v-if="activeTab === 'vendors'" class="space-y-6">
                <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">Vendor</th>
                            <th class="px-4 py-3">Type</th>
                            <th class="px-4 py-3">Transactions</th>
                            <th class="px-4 py-3">Success Rate</th>
                            <th class="px-4 py-3">Avg Latency</th>
                            <th class="px-4 py-3">Gross</th>
                            <th class="px-4 py-3">Realized</th>
                            <th class="px-4 py-3">Failure Impact</th>
                            <th class="px-4 py-3">Net</th>
                            <th class="px-4 py-3">Pending</th>
                            <th class="px-4 py-3">Failed</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100 text-sm">
                        <tr v-for="vendor in vendorPerformance" :key="vendor.vendor_id">
                            <td class="px-4 py-3 font-medium text-gray-900">{{ vendor.vendor_name }}</td>
                            <td class="px-4 py-3 capitalize">{{ vendor.vendor_type }}</td>
                            <td class="px-4 py-3">{{ formatNumber(vendor.total_transactions) }}</td>
                            <td class="px-4 py-3">{{ vendor.success_rate }}%</td>
                            <td class="px-4 py-3">{{ formatNumber(vendor.avg_latency_ms) }}ms</td>
                            <td class="px-4 py-3">{{ formatMoney(vendor.gross_sales) }}</td>
                            <td class="px-4 py-3">{{ formatMoney(vendor.realized_profit || vendor.total_profit) }}</td>
                            <td class="px-4 py-3">{{ formatMoney(vendor.failure_impact) }}</td>
                            <td class="px-4 py-3">{{ formatMoney(vendor.net_profit) }}</td>
                            <td class="px-4 py-3">{{ formatNumber(vendor.pending_count) }}</td>
                            <td class="px-4 py-3">{{ formatNumber(vendor.failed_count) }}</td>
                        </tr>
                        <tr v-if="!vendorPerformance.length">
                            <td colspan="11" class="px-4 py-4 text-center text-xs text-gray-500">No vendor activity in selected range.</td>
                        </tr>
                    </tbody>
                </AppTable>
            </div>

            <div v-if="activeTab === 'reliability'" class="space-y-6">
                <div class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                    <AppCard title="Pending Now" :subtitle="formatNumber(reliability.pending_now)" />
                    <AppCard title="Pending > 15m" :subtitle="formatNumber(reliability.pending_over_15_minutes)" />
                    <AppCard title="Pending > 60m" :subtitle="formatNumber(reliability.pending_over_60_minutes)" />
                    <AppCard title="Stuck Now" :subtitle="formatNumber(reliability.stuck_now)" />
                </div>

                <AppCard title="Top Errors" subtitle="Most frequent execution errors in selected range.">
                    <div class="space-y-2">
                        <div
                            v-for="item in (reliability.top_errors || [])"
                            :key="item.message"
                            class="rounded-md border border-slate-200 px-3 py-2"
                        >
                            <div class="text-xs font-medium text-slate-800">{{ item.message }}</div>
                            <div class="mt-1 text-[11px] text-slate-500">Count: {{ item.total }}</div>
                        </div>
                        <div v-if="!(reliability.top_errors || []).length" class="rounded-md border border-dashed border-slate-300 px-3 py-3 text-xs text-slate-500">
                            No error messages recorded for selected range.
                        </div>
                    </div>
                </AppCard>
            </div>
        </div>
    </AdminLayout>
</template>
