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

const COLORS = {
  accepted: "#27ae60",
  declined: "#e74c3c",
  no_offer: "#95a5a6",
};

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

  if (!data || !Array.isArray(data)) {
    return (
      <div className="arraysubs-retention-chart">
        <h3 className="arraysubs-retention-chart__title">
          {__("Offer Outcomes", "arraysubs")}
        </h3>
        <div className="arraysubs-retention-chart__empty">
          {__("No offer data for this period.", "arraysubs")}
        </div>
      </div>
    );
  }

  const accepted = data
    .filter((item) => item.type && item.type !== "declined")
    .reduce((sum, item) => sum + parseInt(item.count || 0, 10), 0);
  const declined = data
    .filter((item) => item.type === "declined")
    .reduce((sum, item) => sum + parseInt(item.count || 0, 10), 0);
  const chartData = [];

  if (accepted > 0) {
    chartData.push({
      name: __("Accepted", "arraysubs"),
      value: accepted,
      key: "accepted",
    });
  }

  if (declined > 0) {
    chartData.push({
      name: __("Declined", "arraysubs"),
      value: declined,
      key: "declined",
    });
  }

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

  const total = accepted + declined;

  const CustomTooltip = ({ active, payload }) => {
    if (!active || !payload || !payload.length) return null;
    const item = payload[0];
    const percent = total ? ((item.value / total) * 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>
    );
  };

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

  return (
    <div className="arraysubs-retention-chart">
      <h3 className="arraysubs-retention-chart__title">
        {__("Offer Outcomes", "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) => (
                <Cell
                  key={`cell-${entry.key}`}
                  fill={COLORS[entry.key] || "#95a5a6"}
                />
              ))}
            </Pie>
            <Tooltip content={<CustomTooltip />} />
            <Legend />
          </PieChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
};

export default RetentionOfferChart;
