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

function PieCharts( props ) {
 
  let {
    chartLabel = '',
    color1 = '#8884d8',
    cx = '50%',
    cy = '50%',
    dataset,
    height = 400,
    innerRadius,
    key1,
    name1,
    other = 5,
    outerRadius,
    percentage,
  } = props;

  if ( outerRadius ) height = outerRadius * 2.8;

  // Calculate the total value for percentage calculation.

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

  // Process dataset to aggregate small segments into "Other".

  const processedDataset = (() => {

    if (other > 5) other = 5; // Makes no sense to have more than 5% other.

    if (!other || other <= 0) return dataset; // No aggregation if other is 0 or negative.    
    
    const sortedData = [...dataset].sort((a, b) => b[key1] - a[key1]); // Sort dataset by value in descending order.    
    const thresholdValue = (totalValue * other) / 100; // Calculate threshold value.
    
    // Find segments below threshold.
    
    let otherValue = 0;
    const mainSegments = [];
    
    for (const item of sortedData) {

      if (item[key1] < thresholdValue && mainSegments.length > 0) { // This segment is below threshold and we have main segments, add to "Other".
        
        otherValue += item[key1];

      } else { // This segment is above threshold or it's the first/largest segment.
        
        mainSegments.push(item);

      }

    }
    
    // Add "Other" segment if there are aggregated values.

    if (otherValue > 0) {

      mainSegments.push({
        [name1]: 'Other',
        [key1]: otherValue
      });

    }
    
    return mainSegments;

  })();

  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={processedDataset} 
              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;