<script setup lang="ts">
import { integerMoneyToFloat, type Currency } from '@/api/data'
import type { TimeFrame } from './util'
import { onMounted, ref, watch } from 'vue'
import { type ChartOptions, type ChartData, Chart, registerables } from 'chart.js'
import { Pie } from 'vue-chartjs'
import type { AnalyticsApiClient } from '@/api/analytics'

const props = defineProps<{
  timeFrame: TimeFrame
  currency: Currency
  api: AnalyticsApiClient
}>()

const chartData = ref<ChartData<'pie'>>()
const chartOptions = ref<ChartOptions<'pie'>>()

Chart.register(...registerables)

onMounted(() => {
  chartOptions.value = {
    plugins: {
      title: {
        display: true,
        text: 'Category Spend',
      },
    },
  }
})

watch(
  [() => props.currency, () => props.timeFrame],
  async () => {
    buildChartData()
  },
  { immediate: true, deep: true },
)

async function buildChartData() {
  const categorySpendData = await props.api.getCategorySpend(
    props.currency.code,
    props.timeFrame.start ? props.timeFrame.start.getTime() : null,
    props.timeFrame.end ? props.timeFrame.end.getTime() : null,
    null,
  )
  if (categorySpendData.length === 0) {
    chartData.value = undefined
    return
  }

  const labels: string[] = []
  const data: number[] = []
  const colors: string[] = []

  for (const categoryData of categorySpendData) {
    labels.push(categoryData.categoryName ?? 'Uncategorized')
    colors.push(categoryData.categoryColor ? '#' + categoryData.categoryColor : 'white')
    data.push(integerMoneyToFloat(categoryData.amount, props.currency))
  }
  chartData.value = {
    labels: labels,
    datasets: [
      {
        data: data,
        backgroundColor: colors,
      },
    ],
  }
}
</script>
<template>
  <div>
    <Pie
      id="pie"
      v-if="chartData && chartOptions"
      :data="chartData"
      :options="chartOptions"
    />
    <p v-if="!chartData">No category spending data is available for this selection of filters.</p>
  </div>
</template>
