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

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

const chartData = ref<ChartData<'line'>>()
const chartOptions = ref<ChartOptions<'line'> | undefined>()

Chart.register(...registerables)

const COLORS = [
  [255, 69, 69],
  [255, 160, 69],
  [255, 223, 69],
  [118, 255, 69],
  [69, 255, 188],
  [69, 237, 255],
  [69, 125, 255],
  [139, 69, 255],
  [251, 69, 255],
  [255, 69, 167],
]

onMounted(() => {
  chartOptions.value = {
    plugins: {
      title: {
        display: true,
        text: props.title,
      },
    },
    scales: {
      x: {
        type: 'time',
        time: {
          unit: 'day',
        },
      },
    },
  }
})

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

async function buildChartData() {
  const balanceAnalytics = await props.api.getBalanceTimeSeries(
    props.currency.code,
    props.timeFrame.start ? props.timeFrame.start.getTime() : null,
    props.timeFrame.end ? props.timeFrame.end.getTime() : null,
  )

  const datasets: ChartDataset<'line'>[] = []
  let colorIdx = 0

  for (const series of balanceAnalytics.accounts) {
    const color = COLORS[colorIdx++]
    if (colorIdx >= COLORS.length) colorIdx = 0

    const points = series.data.map((p) => {
      return {
        x: p.x,
        y: integerMoneyToFloat(p.y, props.currency),
      }
    })
    datasets.push({
      label: 'Account ' + series.accountId,
      data: points,
      cubicInterpolationMode: 'monotone',
      borderColor: `rgb(${color[0]}, ${color[1]}, ${color[2]})`,
      backgroundColor: `rgba(${color[0]}, ${color[1]}, ${color[2]}, 0.25)`,
      pointRadius: 0,
      borderWidth: 2,
      pointHoverRadius: 5,
      pointHitRadius: 5,
    })
  }
  chartData.value = { datasets: datasets }
}
</script>
<template>
  <div>
    <Line
      v-if="chartData && chartOptions"
      :data="chartData"
      :options="chartOptions"
    />
  </div>
</template>
