<template>
  <Card v-for="chart of charts" :key="chart.health_condition">
    <h2 class="mb-2 text-xl text-violet-900 flex justify-between items-center">
      {{getConditionName(chart.health_condition)}}
    </h2>
    <p class="text-sm text-violet-600"><span class="font-bold">~1 death</span> for every <span class="font-bold">{{Math.round(chart.death_ratio)}} cases ({{Math.round((chart.deaths / chart.cases) * 100)}}%)</span></p>
    <JSCharting :options="chart.options"></JSCharting>
  </Card>
</template>

<script setup>
import { ref, computed } from 'vue'
import { col } from '@/components/charts/util'
import store from '@/components/charts/risk/health-conditions/store.js'

const data = store.data

function getConditionName(condition) {
  if (condition === 'None of the above conditions') return 'No Tracked Conditions'
  if (condition === 'ICU') return 'Admitted to ICU'
  return condition
}

const rows = computed(() => {
  if (!data.value) return []
  return data.value.rows.filter(r => {
    return !['Missing/Unknown status on all conditions','Total with completed information'].includes(col(data, r, 'health_condition'))
  })
})

const charts = computed(() => {
  if (!rows.value) return {}

  const dataSet = Object.values(rows.value.reduce((obj, r) => {
    const sex = col(data, r, 'sex')
    if (sex !== 'Total') return obj
    const health_condition = col(data, r, 'health_condition')

    const cases = col(data, r, 'cases')
    const deaths = col(data, r, 'deaths')

    if (!obj[health_condition]) obj[health_condition] = {
      health_condition,
      cases,
      deaths,
      death_ratio: cases / deaths,
      sort_order: ['Other Chronic Diseases', 'Any Chronic Condition', 'Any Disability', 'None of the above conditions'].includes(health_condition) ? -1 : cases / deaths,
      points: [
        { name: 'Cases', y: cases },
        { name: 'Deaths', y: deaths }
      ]
    }

    return obj
  }, {})).sort((a, b) => a.death_ratio - b.death_ratio)

  if (!dataSet.length) return {}

  dataSet.push(dataSet.splice(dataSet.findIndex(c => c.health_condition === 'Any Disability'), 1).pop())
  dataSet.push(dataSet.splice(dataSet.findIndex(c => c.health_condition === 'Any Chronic Condition'), 1).pop())
  dataSet.push(dataSet.splice(dataSet.findIndex(c => c.health_condition === 'Other Chronic Diseases'), 1).pop())
  dataSet.push(dataSet.splice(dataSet.findIndex(c => c.health_condition === 'None of the above conditions'), 1).pop())

  return dataSet
    .map(({ health_condition, cases, deaths, death_ratio, points }) => ({
      health_condition,
      cases,
      deaths,
      death_ratio,
      options: {
        type: 'gauge linear',
        legend_visible: true,
        legend_position: 'bottom',
        defaultSeries_type: 'column',
        yAxis: { scale_range: [0, points[0].y], visible: false },
        series: [{
          palette: 'default',
          points: points
        }]
      }
    }))
})
</script>
