import React from "react";
import { __ } from "@wordpress/i18n";
import {
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Tooltip,
  Legend,
} from "recharts";

const COLORS = [
  "#e74c3c",
  "#3498db",
  "#2ecc71",
  "#e67e22",
  "#9b59b6",
  "#1abc9c",
  "#f39c12",
  "#34495e",
];

const ChurnReasonsChart = ({ data, loading, totalCancellations }) => {
  if (loading) {
    return (
      <div className="arraysubs-retention-chart arraysubs-retention-chart--loading">
        <div className="arraysubs-retention-chart__skeleton" />
      </div>
    );
  }

  const chartData =
    data && data.length > 0
      ? data.map((item) => ({
          name: item.reason || __("Unknown", "arraysubs"),
          value: parseInt(item.count, 10),
        }))
      : [];

  if (chartData.length === 0) {
    return (
      <div className="arraysubs-retention-chart">
        <h3 className="arraysubs-retention-chart__title">
          {__("Cancellation Reasons", "arraysubs")}
        </h3>
        <div className="arraysubs-retention-chart__empty">
          {__("No cancellation data for this period.", "arraysubs")}
        </div>
      </div>
    );
  }

  const renderLabel = ({ name, percent }) =>
    percent > 0.05 ? `${(percent * 100).toFixed(0)}%` : "";

  const CustomTooltip = ({ active, payload }) => {
    if (!active || !payload || !payload.length) return null;
    const item = payload[0];
    const percent = totalCancellations
      ? ((item.value / totalCancellations) * 100).toFixed(1)
      : 0;

    return (
      <div className="arraysubs-retention-chart__tooltip">
        <p className="arraysubs-retention-chart__tooltip-label">{item.name}</p>
        <p className="arraysubs-retention-chart__tooltip-value">
          {item.value} ({percent}%)
        </p>
      </div>
    );
  };

  return (
    <div className="arraysubs-retention-chart">
      <h3 className="arraysubs-retention-chart__title">
        {__("Cancellation Reasons", "arraysubs")}
      </h3>
      <div className="arraysubs-retention-chart__container">
        <ResponsiveContainer width="100%" height={300}>
          <PieChart>
            <Pie
              data={chartData}
              cx="50%"
              cy="50%"
              outerRadius={100}
              labelLine={false}
              label={renderLabel}
              dataKey="value"
            >
              {chartData.map((entry, index) => (
                <Cell
                  key={`cell-${entry.name}`}
                  fill={COLORS[index % COLORS.length]}
                />
              ))}
            </Pie>
            <Tooltip content={<CustomTooltip />} />
            <Legend />
          </PieChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
};

export default ChurnReasonsChart;
