"use client"

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

interface LineChartProps {
  data: {
    labels: string[]
    datasets: {
      label: string
      data: number[]
      borderColor?: string
      backgroundColor?: string
    }[]
  }
  options?: ChartOptions<"line">
  height?: number
}

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

  const chartData = {
    ...data,
    datasets: data.datasets.map((dataset, index) => ({
      ...dataset,
      borderColor: dataset.borderColor || (index === 0 ? colors.primary : colors.secondary),
      backgroundColor: dataset.backgroundColor || (index === 0 ? `${colors.primary}20` : `${colors.secondary}20`),
      tension: 0.4,
      fill: true,
    })),
  }

  const chartOptions: ChartOptions<"line"> = {
    ...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` }}>
      <Line data={chartData} options={chartOptions} />
    </div>
  )
}
