import {
  Area,
  CartesianGrid,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
  AreaChart,
} from "recharts";
import { TREND_GRANULARITY } from "../../../../utils/raDashboardTrendSeries";
import "../styles/RAPersonalizedWidgets.css";

const TREND_PERIOD_OPTIONS = [
  { value: TREND_GRANULARITY.WEEK, label: "Weekly" },
  { value: TREND_GRANULARITY.MONTH, label: "Monthly" },
  { value: TREND_GRANULARITY.QUARTER, label: "Quarterly" },
  { value: TREND_GRANULARITY.YEAR, label: "Yearly" },
];

/**
 * Risk Assessment admin trend (assigned vs completed) for the personalised dashboard.
 */
export default function RADashboardTrendChart({
  data,
  hasAssignments,
  granularity,
  onGranularityChange,
  caption,
  seriesLabels,
  emptyMessage,
  subtitle,
}) {
  const g = granularity ?? TREND_GRANULARITY.WEEK;
  const assignedLabel = seriesLabels?.assigned ?? "Assigned";
  const completedLabel = seriesLabels?.completed ?? "Completed";

  const axisProps =
    g === TREND_GRANULARITY.YEAR
      ? { angle: 0, textAnchor: "middle", height: 32, tick: { fontSize: 10, fill: "rgba(255,255,255,0.5)" } }
      : g === TREND_GRANULARITY.MONTH || g === TREND_GRANULARITY.QUARTER
        ? {
            angle: -32,
            textAnchor: "end",
            height: 58,
            tick: { fontSize: 9, fill: "rgba(255,255,255,0.5)" },
          }
        : {
            angle: -28,
            textAnchor: "end",
            height: 52,
            tick: { fontSize: 10, fill: "rgba(255,255,255,0.5)" },
          };

  const gid = "pd-ra-adm";
  const assignedStroke = "#f87171";
  const completedStroke = "#34d399";

  const canChangeGranularity = typeof onGranularityChange === "function";

  const emptyMsgDefault =
    "No assigned assessments yet — trend will appear once you assign executors or verifiers.";

  const periodSelector = canChangeGranularity ? (
    <div className="pd-ra-trend-period" role="group" aria-label="Time span">
      {TREND_PERIOD_OPTIONS.map(({ value, label }) => (
        <button
          key={value}
          type="button"
          className={`pd-ra-trend-period-btn${g === value ? " pd-ra-trend-period-btn--active" : ""}`}
          onClick={() => onGranularityChange(value)}
          aria-pressed={g === value}
        >
          {label}
        </button>
      ))}
    </div>
  ) : null;

  if (!hasAssignments) {
    return (
      <div className="pd-ra-trend pd-ra-trend--empty">
        {(periodSelector || subtitle) && (
          <div className="pd-ra-trend-head pd-ra-trend-head--empty">
            <div className="pd-ra-trend-head-intro">
              <span className="pd-ra-trend-title">Assessment trends</span>
              {subtitle ? <p className="pd-ra-trend-subtitle">{subtitle}</p> : null}
            </div>
            {periodSelector}
          </div>
        )}
        <p className="pd-ra-trend-empty-msg">{emptyMessage ?? emptyMsgDefault}</p>
        {caption ? <p className="pd-ra-trend-caption">{caption}</p> : null}
      </div>
    );
  }

  return (
    <div className="pd-ra-trend">
      <div className="pd-ra-trend-head">
        <div className="pd-ra-trend-head-intro">
          <span className="pd-ra-trend-title">Assessment trends</span>
          {subtitle ? <p className="pd-ra-trend-subtitle">{subtitle}</p> : null}
        </div>
        <div className="pd-ra-trend-head-controls">
          {periodSelector}
          <span className="pd-ra-trend-legend-inline" aria-hidden>
            <span className="pd-ra-trend-key pd-ra-trend-key--assigned" /> {assignedLabel}
            <span className="pd-ra-trend-key pd-ra-trend-key--completed" /> {completedLabel}
          </span>
        </div>
      </div>
      <div className="pd-ra-trend-chart-wrap">
        <ResponsiveContainer width="100%" height={220}>
          <AreaChart data={data} margin={{ top: 8, right: 8, left: 0, bottom: 4 }}>
            <defs>
              <linearGradient id={`fillAssigned-${gid}`} x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor={assignedStroke} stopOpacity={0.35} />
                <stop offset="100%" stopColor={assignedStroke} stopOpacity={0.02} />
              </linearGradient>
              <linearGradient id={`fillCompleted-${gid}`} x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor={completedStroke} stopOpacity={0.28} />
                <stop offset="100%" stopColor={completedStroke} stopOpacity={0.02} />
              </linearGradient>
            </defs>
            <CartesianGrid strokeDasharray="4 8" stroke="rgba(255,255,255,0.08)" vertical={false} />
            <XAxis
              dataKey="label"
              interval={0}
              {...axisProps}
              stroke="rgba(255,255,255,0.25)"
              tickLine={false}
              axisLine={false}
            />
            <YAxis
              allowDecimals={false}
              tick={{ fontSize: 10, fill: "rgba(255,255,255,0.45)" }}
              width={36}
              tickLine={false}
              axisLine={false}
            />
            <Tooltip
              contentStyle={{
                borderRadius: 12,
                border: "1px solid rgba(255,255,255,0.12)",
                background: "#2a2828",
                boxShadow: "0 8px 30px rgba(0, 0, 0, 0.35)",
                fontSize: 12,
                color: "rgba(255,255,255,0.92)",
              }}
              labelStyle={{ fontWeight: 600, color: "rgba(255,255,255,0.95)" }}
              formatter={(value, name) => [value, name === "assigned" ? assignedLabel : completedLabel]}
            />
            <Area
              type="monotone"
              dataKey="assigned"
              name="assigned"
              stroke={assignedStroke}
              strokeWidth={2.5}
              fill={`url(#fillAssigned-${gid})`}
              dot={{ r: 0 }}
              activeDot={{ r: 5, strokeWidth: 0 }}
            />
            <Area
              type="monotone"
              dataKey="completed"
              name="completed"
              stroke={completedStroke}
              strokeWidth={2.5}
              fill={`url(#fillCompleted-${gid})`}
              dot={{ r: 0 }}
              activeDot={{ r: 5, strokeWidth: 0 }}
            />
          </AreaChart>
        </ResponsiveContainer>
      </div>
      {caption ? <p className="pd-ra-trend-caption">{caption}</p> : null}
    </div>
  );
}
