<script setup lang="ts">
import { AccountApiClient } from '@/api/account'
import HomeModule from '@/components/HomeModule.vue'
import {
  CategoryScale,
  Chart,
  Filler,
  Legend,
  LinearScale,
  LineElement,
  PointElement,
  TimeScale,
  Title,
  Tooltip,
  type ChartData,
  type ChartDataset,
  type ChartOptions,
} from 'chart.js'
import { getTime } from 'date-fns'
import { onMounted, ref } from 'vue'
import { Line } from 'vue-chartjs'
import { useRoute } from 'vue-router'
import 'chartjs-adapter-date-fns'
import { integerMoneyToFloat } from '@/api/data'
import { AnalyticsApiClient } from '@/api/analytics'

const route = useRoute()

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

Chart.register(
  Title,
  Tooltip,
  Legend,
  LineElement,
  CategoryScale,
  LinearScale,
  PointElement,
  TimeScale,
  Filler,
)

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(async () => {
  const api = new AccountApiClient(route)
  const analyticsApi = new AnalyticsApiClient(route)
  const accounts = await api.getAccounts()
  const timeSeriesData = await analyticsApi.getBalanceTimeSeries()
  const datasets: ChartDataset<'line'>[] = []
  // const timeZoneOffset = -(new Date().getTimezoneOffset())
  let colorIdx = 0

  for (const accountData of timeSeriesData.accounts) {
    if (accountData.currencyCode !== 'USD') continue
    const account = accounts.find((a) => a.id === accountData.accountId)
    if (!account) {
      console.warn("Couldn't find account id " + accountData.accountId)
      continue
    }

    const color = COLORS[colorIdx++]
    const points = accountData.balanceTimeSeries.map((p) => {
      return {
        x: getTime(p.timestamp),
        y: integerMoneyToFloat(p.balance, account.currency),
      }
    })
    datasets.push({
      label: 'Account #' + account.numberSuffix,
      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,
  }
  chartOptions.value = {
    plugins: {
      title: {
        display: true,
        text: 'Account Balances',
      },
    },
    scales: {
      x: {
        type: 'time',
        time: {
          unit: 'day',
        },
      },
    },
  }
})
</script>
<template>
  <HomeModule
    title="Analytics"
    style="min-width: 500px"
  >
    <Line
      v-if="chartData && chartOptions"
      :data="chartData"
      :options="chartOptions"
    />
  </HomeModule>
</template>
