"use client"

import { Bar } from "react-chartjs-2"
import { useTheme } from "next-themes"
import { getChartColors, defaultChartOptions } from "@/lib/chart-config"
import type { ChartOptions } from "chart.js"

interface BarChartProps {
  data: {
    labels: string[]
    datasets: {
      label: string
      data: number[]
      backgroundColor?: string | string[]
    }[]
  }
  options?: ChartOptions<"bar">
  height?: number
  showGrid?: boolean
}

export function BarChart({ data, options, height = 300, showGrid = true }: BarChartProps) {
  const { theme } = useTheme()
  const colors = getChartColors(theme)

  const chartData = {
    ...data,
    datasets: data.datasets.map((dataset) => ({
      ...dataset,
      backgroundColor: dataset.backgroundColor || colors.primary,
      borderRadius: 6,
      borderSkipped: false,
    })),
  }

  const chartOptions: ChartOptions<"bar"> = {
    ...defaultChartOptions,
    ...options,
    scales: {
      y: {
        display: showGrid,
        grid: {
          display: showGrid,
          color: colors.grid,
        },
        ticks: {
          display: showGrid,
          color: colors.text,
        },
      },
      x: {
        grid: {
          display: false,
        },
        ticks: {
          color: colors.text,
        },
      },
    },
    plugins: {
      ...defaultChartOptions.plugins,
      ...options?.plugins,
      legend: {
        display: false,
      },
    },
  }

  return (
    <div style={{ height: `${height}px` }}>
      <Bar data={chartData} options={chartOptions} />
    </div>
  )
}
