<template>
    <div class="default-main annual-report">
        <div class="report-heading">
            <h1>{{ t('user.moneyLog.annualReport.title') }}</h1>
            <el-select v-model="selectedYear" class="year-select" @change="loadReport">
                <el-option v-for="year in yearOptions" :key="year" :label="year" :value="year" />
            </el-select>
        </div>

        <div v-loading="loading" class="report-content">
            <div class="report-table-wrap">
                <table class="report-table">
                    <thead>
                        <tr>
                            <th></th>
                            <th v-for="month in monthLabels" :key="month">{{ month }}</th>
                            <th>{{ t('user.moneyLog.annualReport.year') }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="metric in metrics" :key="metric.key">
                            <th>{{ t(metric.label) }}</th>
                            <td v-for="(value, index) in reportData[metric.key]" :key="index">
                                {{ formatValue(value, metric.currency) }}
                            </td>
                            <td class="year-total">{{ formatValue(reportTotals[metric.key], metric.currency) }}</td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="chart-card">
                <h2>{{ selectedYear }} {{ t('user.moneyLog.annualReport.depositWithdraw') }}</h2>
                <div ref="depositChartRef" class="report-chart"></div>
            </div>

            <div class="chart-card">
                <h2>{{ selectedYear }} {{ t('user.moneyLog.annualReport.transactionActive') }}</h2>
                <div ref="transactionChartRef" class="report-chart"></div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts'
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { annualReport } from '/@/api/backend/user/moneyLog'

defineOptions({
    name: 'user/moneyLog/annualReport',
})

type MetricKey =
    | 'deposit'
    | 'withdraw'
    | 'transactionDeposit'
    | 'transactionWithdraw'
    | 'activePlayer'
    | 'firstDeposit'
    | 'unclaimReceipt'
    | 'unclaimAmount'

type ReportData = Record<MetricKey, number[]>
type ReportTotals = Record<MetricKey, number>

interface ReportTableRow {
    title: string
    year_total: number | string
    [key: `month_${number}`]: number | string
}

const { locale, t } = useI18n()
const currentYear = new Date().getFullYear()
const selectedYear = ref(currentYear)
const loading = ref(false)
const depositChartRef = ref<HTMLElement>()
const transactionChartRef = ref<HTMLElement>()
let depositChart: echarts.ECharts | undefined
let transactionChart: echarts.ECharts | undefined

const monthLabels = computed(() => [
    t('user.moneyLog.annualReport.months.jan'),
    t('user.moneyLog.annualReport.months.feb'),
    t('user.moneyLog.annualReport.months.mar'),
    t('user.moneyLog.annualReport.months.apr'),
    t('user.moneyLog.annualReport.months.may'),
    t('user.moneyLog.annualReport.months.jun'),
    t('user.moneyLog.annualReport.months.jul'),
    t('user.moneyLog.annualReport.months.aug'),
    t('user.moneyLog.annualReport.months.sep'),
    t('user.moneyLog.annualReport.months.oct'),
    t('user.moneyLog.annualReport.months.nov'),
    t('user.moneyLog.annualReport.months.dec'),
])

const metrics: { key: MetricKey; label: string; currency: boolean }[] = [
    { key: 'deposit', label: 'user.moneyLog.annualReport.deposit', currency: true },
    { key: 'withdraw', label: 'user.moneyLog.annualReport.withdraw', currency: true },
    { key: 'transactionDeposit', label: 'user.moneyLog.annualReport.transactionDeposit', currency: false },
    { key: 'transactionWithdraw', label: 'user.moneyLog.annualReport.transactionWithdraw', currency: false },
    { key: 'activePlayer', label: 'user.moneyLog.annualReport.activePlayer', currency: false },
    { key: 'firstDeposit', label: 'user.moneyLog.annualReport.firstDeposit', currency: false },
    { key: 'unclaimReceipt', label: 'user.moneyLog.annualReport.unclaimReceipt', currency: false },
    { key: 'unclaimAmount', label: 'user.moneyLog.annualReport.unclaimAmount', currency: true },
]

const createEmptyReport = (): ReportData => ({
    deposit: Array(12).fill(0),
    withdraw: Array(12).fill(0),
    transactionDeposit: Array(12).fill(0),
    transactionWithdraw: Array(12).fill(0),
    activePlayer: Array(12).fill(0),
    firstDeposit: Array(12).fill(0),
    unclaimReceipt: Array(12).fill(0),
    unclaimAmount: Array(12).fill(0),
})

const createEmptyTotals = (): ReportTotals => ({
    deposit: 0,
    withdraw: 0,
    transactionDeposit: 0,
    transactionWithdraw: 0,
    activePlayer: 0,
    firstDeposit: 0,
    unclaimReceipt: 0,
    unclaimAmount: 0,
})

const reportData = reactive<ReportData>(createEmptyReport())
const reportTotals = reactive<ReportTotals>(createEmptyTotals())
const yearOptions = computed(() => Array.from({ length: 8 }, (_, index) => currentYear - index))

const titleMetricMap: Record<string, MetricKey> = {
    DEPOSIT: 'deposit',
    WITHDRAW: 'withdraw',
    'TRANSACTION (DEPOSIT)': 'transactionDeposit',
    'TRANSACTION (WITHDRAW)': 'transactionWithdraw',
    'ACTIVE PLAYER': 'activePlayer',
    'FIRST DEPOSIT': 'firstDeposit',
    'UNCLAIM RECEIPT': 'unclaimReceipt',
    'UNCLAIM AMOUNT': 'unclaimAmount',
}

const toNumber = (value: unknown) => {
    const number = Number(value)
    return Number.isFinite(number) ? number : 0
}

const normalizeReport = (responseData: any) => {
    const data = createEmptyReport()
    const totals = createEmptyTotals()
    const reportTable = responseData?.report_table ?? responseData?.data?.report_table

    if (!Array.isArray(reportTable)) return { data, totals }

    reportTable.forEach((row: ReportTableRow) => {
        const key = titleMetricMap[String(row.title || '').trim().toUpperCase()]
        if (!key) return

        data[key] = Array.from({ length: 12 }, (_, index) => toNumber(row[`month_${index + 1}`]))
        totals[key] = toNumber(row.year_total)
    })

    return { data, totals }
}

const formatValue = (value: number, currency: boolean) =>
    new Intl.NumberFormat(undefined, {
        minimumFractionDigits: currency ? 2 : 0,
        maximumFractionDigits: currency ? 2 : 0,
    }).format(value)

const chartBaseOption = (): echarts.EChartsOption => ({
    animationDuration: 500,
    grid: { left: 58, right: 24, top: 52, bottom: 70 },
    toolbox: {
        right: 14,
        feature: { saveAsImage: { title: t('user.moneyLog.annualReport.download') } },
    },
    tooltip: { trigger: 'axis' },
    xAxis: {
        type: 'category',
        boundaryGap: false,
        data: monthLabels.value,
        axisLine: { lineStyle: { color: '#d8d8d8' } },
        axisLabel: { color: '#777' },
    },
    yAxis: {
        type: 'value',
        splitLine: { lineStyle: { color: '#ededed' } },
        axisLabel: { color: '#777' },
    },
    dataZoom: [{ type: 'slider', height: 18, bottom: 14, start: 0, end: 100 }, { type: 'inside' }],
})

const renderCharts = () => {
    if (depositChartRef.value) {
        depositChart ||= echarts.init(depositChartRef.value)
        depositChart.setOption({
            ...chartBaseOption(),
            legend: { top: 10, data: [t('user.moneyLog.annualReport.deposit'), t('user.moneyLog.annualReport.withdraw')] },
            series: [
                {
                    name: t('user.moneyLog.annualReport.deposit'),
                    type: 'line',
                    smooth: true,
                    symbolSize: 6,
                    data: reportData.deposit,
                    itemStyle: { color: '#32b36b' },
                    lineStyle: { width: 2 },
                    areaStyle: { color: 'rgba(50, 179, 107, 0.22)' },
                },
                {
                    name: t('user.moneyLog.annualReport.withdraw'),
                    type: 'line',
                    smooth: true,
                    symbolSize: 6,
                    data: reportData.withdraw,
                    itemStyle: { color: '#ef5b5b' },
                    lineStyle: { width: 2 },
                    areaStyle: { color: 'rgba(239, 91, 91, 0.18)' },
                },
            ],
        })
    }

    if (transactionChartRef.value) {
        transactionChart ||= echarts.init(transactionChartRef.value)
        transactionChart.setOption({
            ...chartBaseOption(),
            xAxis: { ...(chartBaseOption().xAxis as object), boundaryGap: true },
            legend: {
                top: 10,
                data: [
                    t('user.moneyLog.annualReport.activePlayer'),
                    t('user.moneyLog.annualReport.transactionDeposit'),
                    t('user.moneyLog.annualReport.transactionWithdraw'),
                ],
            },
            series: [
                {
                    name: t('user.moneyLog.annualReport.activePlayer'),
                    type: 'bar',
                    data: reportData.activePlayer,
                    itemStyle: { color: '#4f8edc' },
                },
                {
                    name: t('user.moneyLog.annualReport.transactionDeposit'),
                    type: 'bar',
                    data: reportData.transactionDeposit,
                    itemStyle: { color: '#32b36b' },
                },
                {
                    name: t('user.moneyLog.annualReport.transactionWithdraw'),
                    type: 'bar',
                    data: reportData.transactionWithdraw,
                    itemStyle: { color: '#f2b441' },
                },
            ],
        })
    }
}

const loadReport = async () => {
    loading.value = true
    try {
        const response = await annualReport({ year: selectedYear.value })
        const normalized = normalizeReport(response.data)
        Object.assign(reportData, normalized.data)
        Object.assign(reportTotals, normalized.totals)
        await nextTick()
        renderCharts()
    } finally {
        loading.value = false
    }
}

const resizeCharts = () => {
    depositChart?.resize()
    transactionChart?.resize()
}

watch(locale, async () => {
    await nextTick()
    renderCharts()
})

onMounted(() => {
    window.addEventListener('resize', resizeCharts)
    loadReport()
})

onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeCharts)
    depositChart?.dispose()
    transactionChart?.dispose()
})
</script>

<style scoped lang="scss">
.annual-report {
    padding: 22px;
    color: var(--el-text-color-primary);
}

.report-heading {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 18px;

    h1 {
        margin: 0;
        font-size: 22px;
        font-weight: 600;
        letter-spacing: 0.3px;
    }
}

.year-select {
    width: 120px;
}

.report-content {
    min-height: 420px;
}

.report-table-wrap {
    overflow-x: auto;
    margin-bottom: 18px;
    background: var(--el-bg-color);
}

.report-table {
    width: 100%;
    min-width: 1080px;
    border-collapse: collapse;
    table-layout: fixed;
    font-size: 12px;

    th,
    td {
        height: 39px;
        padding: 5px 7px;
        border: 1px solid var(--el-border-color);
        background: var(--el-bg-color);
        color: var(--el-text-color-primary);
        text-align: center;
        white-space: nowrap;
    }

    thead th {
        background: var(--el-fill-color-light);
        color: var(--el-text-color-regular);
        font-weight: 600;
    }

    thead th:first-child {
        width: 178px;
    }

    tbody th {
        background: var(--el-fill-color-lighter);
        text-align: left;
        font-weight: 600;
        line-height: 18px;
        white-space: normal;
        overflow-wrap: anywhere;
        word-break: break-word;
    }

    .year-total {
        background: var(--el-fill-color-lighter);
        font-weight: 600;
    }
}

.chart-card {
    margin-bottom: 18px;
    border: 1px solid var(--el-border-color);
    background: var(--el-bg-color);

    h2 {
        margin: 0;
        padding: 12px 16px;
        border-bottom: 1px solid var(--el-border-color);
        background: var(--el-fill-color-light);
        color: var(--el-text-color-primary);
        font-size: 14px;
        font-weight: 600;
    }
}

.report-chart {
    width: 100%;
    height: 300px;
}

@media (max-width: 768px) {
    .annual-report {
        padding: 14px;
    }

    .report-heading h1 {
        font-size: 18px;
    }

    .report-chart {
        height: 260px;
    }
}
</style>
