'use client';

import React from 'react';
import {
  PieChart as RePieChart,
  Pie,
  Cell,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';

type PieDataItem = {
  label: string;
  value: number;
  color?: string;
};

interface PieChartProps {
  data: PieDataItem[];
  donut?: boolean;
  showLegend?: boolean;
  funcss?: string;
  width?: number | string;
  height?: number | string;
}

const getCssVar = (varName: string): string => {
  if (typeof window === 'undefined') return '';
  return (
    getComputedStyle(document.documentElement)
      .getPropertyValue(`--${varName}`)
      ?.trim() || ''
  );
};

const ChartPie: React.FC<PieChartProps> = ({
  data,
  donut = false,
  showLegend = true,
  funcss = '',
  width,
  height,
}) => {
  const resolveColor = (input?: string, fallback = '#8884d8') => {
    if (!input) return getCssVar('primary') || fallback;
    if (input.startsWith('#')) return input;
    return getCssVar(input) || input;
  };

  const chart = (
    <RePieChart width={typeof width === 'number' ? width : undefined} height={typeof height === 'number' ? height : undefined}>
      <Tooltip />
      {showLegend && <Legend />}
      <Pie
        data={data}
        dataKey="value"
        nameKey="label"
        cx="50%"
        cy="50%"
        outerRadius={100}
        innerRadius={donut ? 60 : 0}
        label
      >
        {data.map((entry, index) => (
          <Cell
            key={`cell-${index}`}
            fill={resolveColor(entry.color)}
            stroke="#ffffff"
            strokeWidth={1}
          />
        ))}
      </Pie>
    </RePieChart>
  );

  // If no width or height is set, use ResponsiveContainer
  if (!width && !height) {
    return (
      <ResponsiveContainer width="100%" height={300} className={funcss}>
        {chart}
      </ResponsiveContainer>
    );
  }

  return (
    <div
      className={funcss}
      style={{
        width: typeof width === 'number' ? `${width}px` : width || '100%',
        height: typeof height === 'number' ? `${height}px` : height || '300px',
      }}
    >
      {chart}
    </div>
  );
};

export default ChartPie;
