import React from 'react';
import {
  Chart as ChartJS,
  RadialLinearScale,
  PointElement,
  LineElement,
  Filler,
  Tooltip,
  Legend,
} from 'chart.js';
import { Radar } from 'react-chartjs-2';

ChartJS.register(
  RadialLinearScale,
  PointElement,
  LineElement,
  Filler,
  Tooltip,
  Legend
);

// Define colors based on your theme
const chartColors = {
  amber: '#FF9D00', // Campfire Amber
  dark: '#1A202C', // Campfire Dark
  ash: '#A0AEC0', // Campfire Ash
  light: '#F7FAFC', // Campfire Light
  charcoal: '#2D3748', // Campfire Charcoal
};


function RatingChart({ ratings, labels, size = 'medium' }) {
  // Ensure ratings and labels are valid objects
  if (!ratings || typeof ratings !== 'object' || !labels || typeof labels !== 'object') {
    return <div className="text-center text-campfire-ash">Нет данных для графика.</div>;
  }

  // Filter out ratings that are not numbers or are outside the 1-10 range
  const validRatings = Object.entries(ratings)
    .filter(([key, value]) => typeof value === 'number' && value >= 1 && value <= 10);

  // If no valid ratings, don't render the chart
  if (validRatings.length === 0) {
     return <div className="text-center text-campfire-ash">Нет данных для графика.</div>;
  }

  // Prepare data for the chart
  const chartLabels = validRatings.map(([key]) => labels[key] || key); // Use label if available, otherwise key
  const chartDataValues = validRatings.map(([key, value]) => value);

  const data = {
    labels: chartLabels,
    datasets: [
      {
        label: 'Оценка', // Or 'Средняя оценка' depending on context
        data: chartDataValues,
        backgroundColor: `${chartColors.amber}40`, // Amber with transparency
        borderColor: chartColors.amber,
        pointBackgroundColor: chartColors.amber,
        pointBorderColor: chartColors.light,
        pointHoverBackgroundColor: chartColors.light,
        pointHoverBorderColor: chartColors.amber,
        borderWidth: 2,
        fill: true,
      },
    ],
  };

  const options = {
    responsive: true,
    maintainAspectRatio: size === 'small' ? false : true, // Allow small charts to not maintain aspect ratio
    aspectRatio: size === 'small' ? 1 : (size === 'medium' ? 1.5 : 2), // Adjust aspect ratio based on size
    scales: {
      r: {
        angleLines: {
          display: true,
          color: chartColors.ash + '40', // Ash with transparency
        },
        grid: {
          color: chartColors.ash + '40', // Ash with transparency
        },
        pointLabels: {
          color: chartColors.light, // Light text for labels
          font: {
             size: size === 'small' ? 8 : (size === 'medium' ? 10 : 12), // Adjust font size
          }
        },
        suggestedMin: 0, // Start from 0
        suggestedMax: 10, // Max rating is 10
        ticks: {
          stepSize: 2, // Steps of 2
          color: chartColors.ash, // Ash color for ticks
          backdropColor: chartColors.charcoal, // Background color for tick labels
          font: {
             size: size === 'small' ? 8 : (size === 'medium' ? 10 : 12), // Adjust font size
          }
        },
      },
    },
    plugins: {
      legend: {
        display: false, // Hide legend
      },
      tooltip: {
        callbacks: {
          label: function(context) {
            let label = context.dataset.label || '';
            if (label) {
              label += ': ';
            }
            if (context.raw !== null) {
              label += context.raw.toFixed(1); // Show rating with one decimal place
            }
            return label;
          }
        }
      }
    },
    elements: {
       line: {
          tension: 0.1 // Add some tension for smoother lines
       }
    }
  };

  // Adjust container size based on the 'size' prop
  const containerClasses = size === 'small'
    ? 'w-32 h-32' // Smaller size for individual review items
    : size === 'medium'
      ? 'w-48 h-48 md:w-64 md:h-64' // Medium size for form preview
      : 'w-64 h-64 md:w-80 md:h-80 lg:w-96 lg:h-96'; // Large size for media page aggregate chart


  return (
    <div className={`relative mx-auto ${containerClasses}`}>
      <Radar data={data} options={options} />
    </div>
  );
}

export default RatingChart;
