<script setup lang="ts">
import { computed } from "vue";
import { Bar, Line, Pie } from "vue-chartjs";
import {
  ArcElement,
  BarElement,
  CategoryScale,
  Chart as ChartJS,
  Legend,
  LinearScale,
  LineElement,
  PointElement,
  Tooltip,
} from "chart.js";
import Card from "../ui/Card.vue";
import CardContent from "../ui/CardContent.vue";
import CardHeader from "../ui/CardHeader.vue";
import CardTitle from "../ui/CardTitle.vue";

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  LineElement,
  PointElement,
  ArcElement,
  Tooltip,
  Legend,
);

const props = defineProps<{
  data: {
    type?: "bar" | "line" | "pie";
    dataset?: Record<string, unknown>;
  };
  widget: {
    key: string;
    label: string;
    width: string;
    hideable: boolean;
  };
}>();

const chartComponent = computed(() => {
  switch (props.data.type) {
    case "line":
      return Line;
    case "pie":
      return Pie;
    default:
      return Bar;
  }
});

const chartOptions = {
  responsive: true,
  maintainAspectRatio: true,
  plugins: {
    legend: { position: "bottom" as const },
  },
};
</script>

<template>
  <Card class="h-full">
    <CardHeader>
      <CardTitle>{{ widget.label }}</CardTitle>
    </CardHeader>
    <CardContent>
      <component
        :is="chartComponent"
        v-if="data.dataset"
        :data="data.dataset"
        :options="chartOptions"
      />
      <p v-else class="text-sm text-muted-foreground">No chart data.</p>
    </CardContent>
  </Card>
</template>
