<script lang="ts" setup>
import { computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
} from 'echarts/components'
import VChart from 'vue-echarts'
import { useTheme } from 'vuetify'

use([CanvasRenderer, BarChart, LineChart, PieChart, GridComponent, TooltipComponent, LegendComponent])

interface Props {
  type: 'bar' | 'line' | 'pie'
  data: Array<Record<string, unknown>>
  title?: string
  xAxisLabel?: string
  yAxisLabel?: string
  nameKey?: string
  valueKey?: string
}

const props = withDefaults(defineProps<Props>(), {
  title: undefined,
  xAxisLabel: undefined,
  yAxisLabel: undefined,
  nameKey: 'name',
  valueKey: 'value',
})

const theme = useTheme()
const isDark = computed<boolean>(() => theme.global.current.value.dark)

const chartTextColor = computed<string>(() => isDark.value ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.6)')
const chartLineColor = computed<string>(() => isDark.value ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.08)')

const colors = ['#1d4ed8', '#3b82f6', '#60a5fa', '#93c5fd', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6']

const chartOption = computed(() => {
  if (props.type === 'pie') {
    return {
      tooltip: {
        trigger: 'item' as const,
        backgroundColor: isDark.value ? 'rgba(30,41,59,0.95)' : 'rgba(255,255,255,0.95)',
        borderColor: isDark.value ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)',
        textStyle: { color: isDark.value ? '#e2e8f0' : '#1e293b', fontSize: 12 },
      },
      legend: {
        orient: 'horizontal' as const,
        bottom: 0,
        textStyle: { color: chartTextColor.value, fontSize: 11 },
        icon: 'roundRect',
        itemWidth: 14,
        itemHeight: 8,
      },
      series: [{
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: true,
        itemStyle: { borderRadius: 6, borderColor: isDark.value ? '#1e293b' : '#fff', borderWidth: 2 },
        label: { show: false },
        emphasis: { label: { show: true, fontSize: 13, fontWeight: 'bold' } },
        data: props.data.map((item, idx) => ({
          name: item[props.nameKey] as string,
          value: item[props.valueKey] as number,
          itemStyle: { color: colors[idx % colors.length] },
        })),
      }],
    }
  }

  const names = props.data.map(item => item[props.nameKey] as string)
  const values = props.data.map(item => item[props.valueKey] as number)

  return {
    tooltip: {
      trigger: 'axis' as const,
      backgroundColor: isDark.value ? 'rgba(30,41,59,0.95)' : 'rgba(255,255,255,0.95)',
      borderColor: isDark.value ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)',
      textStyle: { color: isDark.value ? '#e2e8f0' : '#1e293b', fontSize: 12 },
    },
    grid: { left: 70, right: 30, top: 20, bottom: 40 },
    xAxis: {
      type: 'category' as const,
      data: names,
      axisLabel: { color: chartTextColor.value, fontSize: 11, rotate: names.length > 8 ? 45 : 0 },
      axisLine: { lineStyle: { color: chartLineColor.value } },
      axisTick: { show: false },
    },
    yAxis: {
      type: 'value' as const,
      axisLabel: {
        color: chartTextColor.value,
        fontSize: 11,
        formatter: (v: number) => v >= 1000 ? `$${(v / 1000).toFixed(0)}k` : `$${v}`,
      },
      splitLine: { lineStyle: { color: chartLineColor.value } },
    },
    series: [{
      type: props.type,
      data: values,
      smooth: props.type === 'line',
      symbol: props.type === 'line' ? 'circle' : undefined,
      symbolSize: props.type === 'line' ? 6 : undefined,
      lineStyle: props.type === 'line' ? { width: 3, color: '#3b82f6' } : undefined,
      itemStyle: { color: '#1d4ed8', borderRadius: props.type === 'bar' ? [4, 4, 0, 0] : undefined },
      areaStyle: props.type === 'line' ? {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(29,78,216,0.25)' },
            { offset: 1, color: 'rgba(29,78,216,0.02)' },
          ],
        },
      } : undefined,
    }],
  }
})
</script>

<template>
  <div>
    <div v-if="title" class="text-subtitle-2 text-medium-emphasis mb-2">
      {{ title }}
    </div>
    <VChart :option="chartOption" autoresize style="height: 320px;" />
  </div>
</template>
