"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
    }[]
  }
  options?: ChartOptions<"bar">
  height?: number
}

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

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

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

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