import { 
  Pie,
  PieChart,
  ResponsiveContainer,
  Tooltip
} from 'recharts';

function PieCharts( props ) {
 
  let {
    chartLabel,
    color1,
    cx,
    cy,
    dataset,
    height,
    innerRadius,
    key1,
    name1,
    outerRadius,
    percentage,
  } = props;

  if ( outerRadius ) height = outerRadius * 2.8;

  if ( !color1 ) color1 = "#8884d8";

  if ( !cx ) cx = '50%';

  if ( !cy ) cy = '50%';
 
  if ( !height ) height = 400;

  // Calculate the total value for percentage calculation

  const totalValue = dataset.reduce((sum, item) => sum + item[key1], 0);

  return (

    <div className="mt-3 mb-3">

      {chartLabel && <div className="size-65" dangerouslySetInnerHTML={{ __html: chartLabel }} />}
      
      <div className="size-65">

        <ResponsiveContainer width="100%" height={height}>

          <PieChart>

            <Pie 
              cx={cx} 
              cy={cy} 
              data={dataset} 
              dataKey={key1} 
              fill={color1}
              innerRadius={innerRadius}
              nameKey={name1} 
              outerRadius={outerRadius} 
              label={({ name, value }) => {

                // If percentage is true, calculate percentage; otherwise, show value

                return percentage
                  ? `${name} (${((value / totalValue) * 100).toFixed(2)}%)`
                  : `${name} (${value})`;

              }}

            />

            <Tooltip />

          </PieChart>
          
        </ResponsiveContainer>

      </div>

    </div>
      
  );

}

export default PieCharts;