'use client';

import React from 'react';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  Tooltip,
  Legend,
  CartesianGrid,
  ResponsiveContainer,
} from 'recharts';

type DataItem = {
  label: string;
  [key: string]: any;
};

type ChartSeries = {
  dataKey: string;
  label?: string;
  color?: string; // Can be a CSS variable name like 'primary' or a hex code
};

interface BarsProps {
  data: DataItem[];
  series: ChartSeries[];
  showGrid?: boolean;
  funcss?: string,
  showLegend?: boolean;
  showXAxis?: boolean;
  showYAxis?: boolean;
  barRadius?: number;
  barSize?: number;
}

// Resolve 'primary' to actual CSS variable value like var(--primary)
const resolveColor = (color?: string): string => {
  if (!color) return getCssVar('--primary') || '#8884d8';
  if (color.startsWith('#')) return color;
  return getCssVar(`--${color}`) || color;
};

// Helper to get CSS variable value from :root
const getCssVar = (varName: string): string => {
  if (typeof window === 'undefined') return '';
  return getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
};

const Bars: React.FC<BarsProps> = ({
  data,
  series,
  showGrid = true,
  showLegend = true,
  showXAxis = true,
  showYAxis = false,
  barRadius = 6,
  funcss,
  barSize = 30,
  ...rest
}) => {
  return (
    <ResponsiveContainer className={funcss || ``} {...rest} width="100%" >
      <BarChart data={data}>
        {showGrid && <CartesianGrid strokeDasharray="3 3" />}
        {showXAxis && <XAxis dataKey="label" />}
        {showYAxis && <YAxis />}
        <Tooltip />
        {showLegend && <Legend />}
        {series.map((s) => (
          <Bar
            key={s.dataKey}
            dataKey={s.dataKey}
            name={s.label || s.dataKey}
            fill={resolveColor(s.color)}
            radius={[barRadius, barRadius, 0, 0]}
            barSize={barSize}
          />
        ))}
      </BarChart>
    </ResponsiveContainer>
  );
};

export default Bars;
