import React from "react";
import { useNavigate } from "react-router-dom";
import {
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
  Legend,
  Tooltip,
} from "recharts";
import AddToPersonalizedButton from "../common/AddToPersonalizedButton";
import StatCard from "../common/StatCard";
import "../styles/SioOioCaCharts.css";

const SIO_OIO_CA_COLORS = { SIO: "#2563eb", OIO: "#ea580c", CA: "#16a34a" };

const sioIcon = (
  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M12 2v4m0 12v4M2 12h4m12 0h4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    <circle cx="12" cy="12" r="4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);
const oioIcon = (
  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
    <circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    <path d="M12 2v2m0 16v2M2 12h2m16 0h2" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);
const sioPaIcon = (
  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M20 6L9 17l-5-5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);

const SioOioCaCharts = ({ data, showOnly }) => {
  const navigate = useNavigate();
  const showPie = showOnly !== "cards";
  const showCards = showOnly !== "pie";
  const sioCount = data?.sioCount ?? 0;
  const oioCount = data?.oioCount ?? 0;
  const caCount = data?.caCount ?? 0;
  const total = data?.total ?? 0;
  const sioPercentage = data?.sioPercentage ?? 0;
  const oioPercentage = data?.oioPercentage ?? 0;
  const caPercentage = data?.caPercentage ?? 0;
  const sioPaPercentage = data?.sioPaPercentage ?? 0;

  const pieData = [
    { name: "SIO", value: sioCount, percentage: sioPercentage, key: "SIO" },
    { name: "OIO", value: oioCount, percentage: oioPercentage, key: "OIO" },
    { name: "CA", value: caCount, percentage: caPercentage, key: "CA" },
  ].filter((d) => d.value > 0);

  const hasPieData = pieData.length > 0;
  const displayPieData = hasPieData
    ? pieData
    : [{ name: "No SIO/OIO/CA data yet", value: 1, key: "empty" }];

  const RADIAN = Math.PI / 180;
  const renderLabel = ({
    cx,
    cy,
    midAngle,
    innerRadius,
    outerRadius,
    percent,
    value,
  }) => {
    if (!hasPieData || percent < 0.05) return null;
    const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
    const x = cx + radius * Math.cos(-midAngle * RADIAN);
    const y = cy + radius * Math.sin(-midAngle * RADIAN);
    return (
      <text
        x={x}
        y={y}
        fill="white"
        textAnchor="middle"
        dominantBaseline="central"
        className="sio-oio-ca-pie-label"
      >
        {value != null ? String(value) : ""}
      </text>
    );
  };

  const tooltipFormatter = (value, name, props) => {
    if (!hasPieData) return [value, name];
    const pct = props?.payload?.percentage;
    return [`${value} (${pct != null ? pct.toFixed(1) : "0"}%)`, name];
  };

  const handlePieSegmentClick = (entry) => {
    if (!hasPieData || !entry || entry.key === "empty") return;
    navigate(`/dashboard/sio-oio-ca-list?type=${encodeURIComponent(entry.key)}`);
  };

  const handlePieContainerClick = () => {
    const defaultType = hasPieData && pieData.length ? pieData[0].key : "SIO";
    navigate(`/dashboard/sio-oio-ca-list?type=${encodeURIComponent(defaultType)}`);
  };

  const PieIcon = () => (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
      <path d="M21.21 15.89A10 10 0 1 1 8 2.83" />
      <path d="M22 12A10 10 0 0 0 12 2v10z" />
    </svg>
  );

  const percentageStats = [
    {
      label: "SIO %",
      value: `${sioPercentage.toFixed(1)}%`,
      icon: sioIcon,
      description: "Share of observations that are SIO (Significant Impact Observation) out of all SIO, OIO and CA.",
    },
    {
      label: "OIO %",
      value: `${oioPercentage.toFixed(1)}%`,
      icon: oioIcon,
      description: "Share of observations that are OIO (Other Impact Observation) out of all SIO, OIO and CA.",
    },
    {
      label: "SIO PA %",
      value: `${sioPaPercentage.toFixed(1)}%`,
      icon: sioPaIcon,
      description: "Percentage of SIO audits that are closed (SIO PA = SIO Preventive Action closed).",
    },
  ];
  const percentageWidgetIds = ["sioPctCard", "oioPctCard", "sioPaPctCard"];

  return (
    <div className="sio-oio-ca-wrapper">
      {showPie && (
      <div
        className="sio-oio-ca-card sio-oio-ca-pie-container chart-card chart-card--has-add-btn sio-oio-ca-clickable"
        onClick={handlePieContainerClick}
        onKeyDown={(e) => {
          if (e.key === "Enter" || e.key === " ") {
            e.preventDefault();
            handlePieContainerClick();
          }
        }}
        role="button"
        tabIndex={0}
        aria-label="SIO, OIO, CA distribution. Click to view audit details."
      >
        <AddToPersonalizedButton widgetId="sioOioCaPie" />
        <div className="sio-oio-ca-card-header">
          <div className="sio-oio-ca-card-icon sio-oio-ca-card-icon--pie">
            <PieIcon />
          </div>
          <div className="sio-oio-ca-card-heading">
            <h2 className="sio-oio-ca-pie-title">Observation types</h2>
            <p className="sio-oio-ca-pie-subtitle">
              SIO, OIO & CA — Total: <strong>{total}</strong>. Click segment or chart to view details.
            </p>
          </div>
        </div>
        <div className="sio-oio-ca-pie-chart-wrap">
        <ResponsiveContainer width="100%" height={280}>
          <PieChart>
            <Pie
              data={displayPieData}
              cx="50%"
              cy="50%"
              labelLine={false}
              label={hasPieData ? renderLabel : undefined}
              outerRadius={90}
              innerRadius={50}
              dataKey="value"
              nameKey="name"
              onClick={(data, index, evt) => {
                evt?.stopPropagation?.();
                handlePieSegmentClick(displayPieData[index]);
              }}
              style={{ cursor: hasPieData ? "pointer" : "default" }}
            >
              {displayPieData.map((entry, index) => (
                <Cell
                  key={entry.key || entry.name}
                  fill={hasPieData ? SIO_OIO_CA_COLORS[entry.key] || "#94a3b8" : "#e5e7eb"}
                />
              ))}
            </Pie>
            <Tooltip formatter={tooltipFormatter} />
            <Legend
              verticalAlign="bottom"
              height={36}
              formatter={(value, entry) => (
                <span className="sio-oio-ca-legend-item">
                  <span
                    className="sio-oio-ca-legend-dot"
                    style={{ background: entry.color }}
                  />
                  {value}
                </span>
              )}
            />
          </PieChart>
        </ResponsiveContainer>
        </div>
      </div>
      )}

      {showCards && (
      <div className="sio-oio-ca-percentage-cards">
        {percentageStats.map((stat, index) => (
          <div
            key={index}
            className={`dashboard-stat-card-wrap dashboard-stat-card-wrap--has-add-btn ${index === 2 ? "sio-oio-ca-pct-card--full-width" : ""}`}
          >
            <AddToPersonalizedButton widgetId={percentageWidgetIds[index]} />
            <StatCard stat={stat} index={index} />
          </div>
        ))}
      </div>
      )}
    </div>
  );
};

export default SioOioCaCharts;
