'use client';

import React, { useEffect, useState } from 'react';
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  Tooltip,
  Legend,
  CartesianGrid,
  ResponsiveContainer,
} from 'recharts';

type DataItem = {
  label: string;
  [key: string]: any;
};

type ChartSeries = {
  dataKey: string;
  label?: string;
  color?: string;
  strokeWidth?: number;
  dot?: boolean;
  fromColor?: string;
  toColor?: string;
};

interface AreaChartProps {
  data: DataItem[];
  series: ChartSeries[];
  fromColor?: string;
  toColor?: string;
  showGrid?: boolean;
  showLegend?: boolean;
  showXAxis?: boolean;
  showYAxis?: boolean;
  funcss?: string;
  curveType?: 'linear' | 'monotone' | 'step' | 'basis';
}

const getCssVar = (varName: string): string => {
  if (typeof window === 'undefined') return '';
  return getComputedStyle(document.documentElement).getPropertyValue(`--${varName}`)?.trim() || '';
};
 



const resolveStrokeColor = (color?: string): string => {
  if (!color) return getCssVar('primary') || '#8884d8';
  if (color.startsWith('#')) return color;
  return getCssVar(color) || color;
};

const Lines: React.FC<AreaChartProps> = ({
  data,
  series,
  fromColor,
  toColor,
  showGrid = true,
  showLegend = true,
  showXAxis = true,
  showYAxis = false,
  funcss,
  curveType = 'monotone',
}) => {
  return (
    <ResponsiveContainer width="100%"  className={funcss}>
      <AreaChart data={data}>


 <defs>
    <linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">
      <stop offset="5%" stopColor={getCssVar(fromColor || 'primary')} stopOpacity={0.8}/>
      <stop offset="95%" stopColor={getCssVar(toColor || 'primary200')} stopOpacity={0}/>
    </linearGradient>
  </defs>

        {showGrid && <CartesianGrid strokeDasharray="3 3" />}
        {showXAxis && <XAxis dataKey="label" angle={45} />}
        {showYAxis && <YAxis />}
        <Tooltip />
        {showLegend && <Legend />}
        {series.map((s, index) => (
          <Area
            key={s.dataKey}
            type={curveType}
            dataKey={s.dataKey}
            name={s.label || s.dataKey}
            stroke={resolveStrokeColor(s.color)}
            fill="url(#colorUv)"
            fillOpacity={1}
            strokeWidth={s.strokeWidth || 2}
            dot={s.dot !== false ? { r: 4 } : false}
            activeDot={{ r: 8 }}
          />
        ))}
      </AreaChart>
    </ResponsiveContainer>
  );
};

export default Lines;
