<script setup lang="ts">
import { computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useAdminDashboard } from '../../composables/useAdminDashboard';
import EChartPanel from '../../components/dashboard/EChartPanel.vue';
import { buildCombinedTrendOption, buildTriplePieOption, buildBarChartOption } from '../../utils/dashboard-charts';
import { betStatusLabel } from '../../utils/bet-labels';
import { useAdminLocale } from '../../composables/useAdminLocale';
import { usePermissions } from '../../composables/usePermissions';

const { t } = useAdminLocale();
const { role } = usePermissions();
const isMatchOperatorView = computed(() => role.value === 'MATCH_ADMIN');
const router = useRouter();
const {
  s,
  loading,
  loadError,
  load,
  formatTime,
  toNum,
  chartI18n,
  trendLabels,
  kpiPrimary,
  fmtCount,
} = useAdminDashboard();

onMounted(() => {
  void load();
});

type KpiLink = { path: string; query?: Record<string, string> };

function goKpiLink(link: KpiLink) {
  router.push(link.query ? { path: link.path, query: link.query } : link.path);
}

const mainTrendOption = computed(() => {
  const counts = s.value?.trend7d?.map((d) => d.betCount) ?? [];
  if (isMatchOperatorView.value) {
    return buildBarChartOption(
      trendLabels.value,
      [{ name: t('dash.chart_bet_count'), color: '#956400', values: counts }],
      { amountAxis: false },
    );
  }
  return buildCombinedTrendOption(
    trendLabels.value,
    [
      {
        name: t('dash.chart_stake'),
        color: '#346538',
        values: s.value?.trend7d?.map((d) => toNum(d.stake)) ?? [],
      },
      {
        name: t('dash.chart_payout'),
        color: '#1f6c9f',
        values: s.value?.trend7d?.map((d) => toNum(d.payout)) ?? [],
      },
      {
        name: t('dash.chart_ggr'),
        color: '#956400',
        values: s.value?.trend7d?.map((d) => toNum(d.ggr)) ?? [],
      },
    ],
    counts,
    chartI18n.value,
  );
});

const distributionOption = computed(() => {
  const m = s.value?.matches;
  const raw = s.value?.bets.todayByStatus ?? {};
  const betColors: Record<string, string> = {
    PENDING: '#956400',
    WON: '#346538',
    LOST: '#9f2f2d',
    VOID: '#8c867c',
    REFUNDED: '#1f6c9f',
  };

  const matchSegs = m
    ? [
        { label: t('dash.match_draft'), value: m.draft, color: '#8c867c' },
        { label: t('dash.match_published'), value: m.published, color: '#346538' },
        { label: t('dash.match_closed'), value: m.closed, color: '#1f6c9f' },
        { label: t('dash.match_pending_settle'), value: m.pendingSettlement, color: '#956400' },
        { label: t('dash.match_settled'), value: m.settled ?? 0, color: '#477a4c' },
      ].filter((x) => x.value > 0)
    : [];

  const betSegs = ['PENDING', 'WON', 'LOST', 'VOID', 'REFUNDED']
    .filter((k) => raw[k]?.count)
    .map((k) => ({
      label: betStatusLabel(k),
      value: raw[k].count,
      color: betColors[k] ?? '#8c867c',
    }));

  return buildTriplePieOption(
    [
      { title: t('dash.pie_matches'), segments: matchSegs },
      { title: t('dash.pie_bets'), segments: betSegs },
      { title: '', segments: [] },
    ],
    chartI18n.value,
  );
});

const kpiMatch = computed(() => {
  if (!s.value) return [];
  const m = s.value.matches;
  const pendingMatches = m.pendingSettlement ?? 0;
  return [
    {
      label: t('dash.kpi_match_total'),
      value: fmtCount(m.total),
      sub: t('dash.kpi_match_total_sub', {
        draft: fmtCount(m.draft),
        published: fmtCount(m.published),
      }),
    },
    {
      label: t('dash.kpi_match_closed'),
      value: fmtCount(m.closed),
      sub: t('dash.kpi_match_closed_sub', { n: fmtCount(m.cancelled ?? 0) }),
    },
    {
      label: t('dash.kpi_pending'),
      value: `${fmtCount(s.value.bets.pendingTotal)} ${t('common.bets_unit')}`,
      sub: t('dash.kpi_pending_sub', {
        bets: fmtCount(s.value.bets.pendingTotal),
        matches: fmtCount(pendingMatches),
      }),
      link:
        pendingMatches > 0
          ? { path: '/matches', query: { status: 'PENDING_SETTLEMENT' } }
          : undefined,
    },
    {
      label: t('dash.kpi_match_settled'),
      value: fmtCount(m.settled ?? 0),
      sub: t('dash.kpi_match_settled_sub'),
    },
  ];
});
</script>

<template>
  <div class="dashboard-page" v-loading="loading">
    <el-card v-if="!loading && loadError" class="state-card" shadow="never">
      <p class="state-title">{{ t('msg.load_failed') }}</p>
      <p class="state-hint">{{ t('dash.load_error_hint') }}</p>
      <el-button type="primary" size="small" @click="load(true)">{{ t('common.retry') }}</el-button>
    </el-card>

    <template v-else-if="s">
      <el-card class="overview-board" shadow="never">
        <div v-if="s.generatedAt" class="board-head">
          <span class="board-hint">{{
            isMatchOperatorView ? t('dash.section_match_ops_hint') : t('dash.section_matches_hint')
          }}</span>
          <span class="dash-updated">
            {{ t('common.updated_at') }} {{ formatTime(s.generatedAt) }}
          </span>
        </div>

        <div v-if="!isMatchOperatorView" class="kpi-grid kpi-primary">
          <div v-for="item in kpiPrimary" :key="item.label" class="kpi-cell">
            <span class="kpi-label">{{ item.label }}</span>
            <span class="kpi-value">{{ item.value }}</span>
            <span class="kpi-sub">{{ item.sub }}</span>
            <span
              class="kpi-delta"
              :class="{ up: item.delta.startsWith('+'), down: item.delta.startsWith('-') }"
            >
              {{ t('common.vs_yesterday') }} {{ item.delta }}
            </span>
          </div>
        </div>

        <div class="kpi-grid" :class="isMatchOperatorView ? 'kpi-primary' : 'kpi-secondary'">
          <div
            v-for="item in kpiMatch"
            :key="item.label"
            class="kpi-cell compact"
            :class="{ 'kpi-cell--link': item.link }"
            :role="item.link ? 'button' : undefined"
            :tabindex="item.link ? 0 : undefined"
            @click="item.link && goKpiLink(item.link)"
            @keydown.enter.prevent="item.link && goKpiLink(item.link)"
          >
            <span class="kpi-label">{{ item.label }}</span>
            <span class="kpi-value sm">{{ item.value }}</span>
            <span class="kpi-sub">{{ item.sub }}</span>
          </div>
        </div>

        <div class="charts-stack">
          <EChartPanel title="" :option="mainTrendOption" height="300px" class="chart-main" />
          <div class="chart-main-caption">{{
            isMatchOperatorView ? t('dash.trend_bet_count_caption') : t('dash.trend_caption')
          }}</div>
          <EChartPanel title="" :option="distributionOption" height="200px" class="chart-dist" />
        </div>
      </el-card>
    </template>
  </div>
</template>

<style scoped>
@import './dashboard-board.css';
</style>
