"use client"

import {
  LineChart as RechartsLineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  BarChart as RechartsBarChart,
  Bar,
  PieChart as RechartsPieChart,
  Pie,
  Cell,
} from "recharts"

interface ChartProps {
  data: any
  height?: number
}

export function LineChart({ data, height = 300 }: ChartProps) {
  return (
    <ResponsiveContainer width="100%" height={height}>
      <RechartsLineChart
        data={data.labels.map((label, i) => {
          const dataPoint = { name: label }
          data.datasets.forEach((dataset, j) => {
            dataPoint[dataset.label] = dataset.data[i]
          })
          return dataPoint
        })}
      >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="name" />
        <YAxis />
        <Tooltip />
        <Legend />
        {data.datasets.map((dataset, i) => (
          <Line
            key={i}
            type="monotone"
            dataKey={dataset.label}
            stroke={dataset.borderColor}
            fill={dataset.backgroundColor}
            activeDot={{ r: 8 }}
          />
        ))}
      </RechartsLineChart>
    </ResponsiveContainer>
  )
}

export function BarChart({ data, height = 300 }: ChartProps) {
  return (
    <ResponsiveContainer width="100%" height={height}>
      <RechartsBarChart
        data={data.labels.map((label, i) => {
          const dataPoint = { name: label }
          data.datasets.forEach((dataset, j) => {
            dataPoint[dataset.label] = dataset.data[i]
          })
          return dataPoint
        })}
      >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="name" />
        <YAxis />
        <Tooltip />
        <Legend />
        {data.datasets.map((dataset, i) => (
          <Bar key={i} dataKey={dataset.label} fill={dataset.backgroundColor || "#8884d8"} />
        ))}
      </RechartsBarChart>
    </ResponsiveContainer>
  )
}

export function PieChart({ data, height = 300 }: ChartProps) {
  return (
    <ResponsiveContainer width="100%" height={height}>
      <RechartsPieChart>
        <Pie
          data={data.labels.map((label, i) => ({
            name: label,
            value: data.datasets[0].data[i],
          }))}
          cx="50%"
          cy="50%"
          labelLine={false}
          outerRadius={80}
          fill="#8884d8"
          dataKey="value"
          label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
        >
          {data.labels.map((entry, index) => (
            <Cell
              key={`cell-${index}`}
              fill={data.datasets[0].backgroundColor[index] || `#${Math.floor(Math.random() * 16777215).toString(16)}`}
            />
          ))}
        </Pie>
        <Tooltip />
        <Legend />
      </RechartsPieChart>
    </ResponsiveContainer>
  )
}
