import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
  Area,
  AreaChart,
  CartesianGrid,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis
} from "recharts";
import { getDashboardStats } from "../../services/dashboardApi.js";
import { PTW_TREND_PERIOD_OPTIONS, handleDashboardActivate } from "../../utils/dashboardHelpers.js";
import "./PermitTrendChart.css";

const CREATED_STROKE = "#8b1538";
const CLOSED_STROKE = "#189e52";

function axisPropsForPeriod(period) {
  if (period === "year") {
    return {
      angle: 0,
      textAnchor: "middle",
      height: 32,
      tick: { fontSize: 10, fill: "var(--ex-muted, #737373)" }
    };
  }
  if (period === "30d" || period === "90d") {
    return {
      angle: -32,
      textAnchor: "end",
      height: 58,
      tick: { fontSize: 9, fill: "var(--ex-muted, #737373)" }
    };
  }
  return {
    angle: -28,
    textAnchor: "end",
    height: 52,
    tick: { fontSize: 10, fill: "var(--ex-muted, #737373)" }
  };
}

function mapTrendRows(rows = []) {
  return rows.map((row) => ({
    label: row.label,
    assigned: Number(row.count) || 0,
    completed: Number(row.closed) || 0
  }));
}

function TrendShell({
  subtitle,
  periodSelector,
  variant = "",
  children,
  onChartClick
}) {
  const clickable = Boolean(onChartClick);
  return (
    <section className="ptw-dashboard-trend-section" aria-label="Permit trends">
      <div className={`ex-dash ptw-trend-chart-embed${clickable ? " ptw-trend-chart-embed--clickable" : ""}`}>
        <div className={`ex-dash-trend ex-dash-trend--role-admin${variant ? ` ${variant}` : ""}`}>
          <div className={`ex-dash-trend-head${variant.includes("empty") ? " ex-dash-trend-head--empty" : ""}`}>
            <div className="ex-dash-trend-head-intro">
              <span className="ex-dash-trend-title">Permits trends</span>
              {subtitle ? (
                <p className="ex-dash-trend-subtitle">
                  {clickable ? `${subtitle} Click the chart to view permits.` : subtitle}
                </p>
              ) : null}
            </div>
            <div
              className="ex-dash-trend-head-controls"
              onClick={(event) => event.stopPropagation()}
              onKeyDown={(event) => event.stopPropagation()}
            >
              {periodSelector}
              {!variant ? (
                <span className="ex-dash-trend-legend-inline" aria-hidden>
                  <span className="ex-dash-trend-key ex-dash-trend-key--assigned" /> Created
                  <span className="ex-dash-trend-key ex-dash-trend-key--completed" /> Closed
                </span>
              ) : null}
            </div>
          </div>
          {clickable && !variant ? (
            <div
              className="ex-dash-trend-chart-wrap ex-dash-trend-chart-wrap--clickable"
              role="button"
              tabIndex={0}
              aria-label="Open permits and submissions"
              onClick={onChartClick}
              onKeyDown={(event) => handleDashboardActivate(event, onChartClick)}
            >
              {children}
            </div>
          ) : (
            children
          )}
        </div>
      </div>
    </section>
  );
}

export default function PermitTrendChart({
  refreshSignal = 0,
  subtitle = "Created and closed permits over time",
  onNavigate
}) {
  const [period, setPeriod] = useState("30d");
  const [chartRows, setChartRows] = useState([]);
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState("");

  const loadTrend = useCallback(async () => {
    setLoading(true);
    setLoadError("");
    try {
      const stats = await getDashboardStats(period);
      setChartRows(mapTrendRows(stats?.trend));
    } catch (err) {
      setLoadError(err?.response?.data?.message || err.message);
      setChartRows([]);
    } finally {
      setLoading(false);
    }
  }, [period]);

  useEffect(() => {
    loadTrend();
  }, [loadTrend, refreshSignal]);

  const hasPermits = useMemo(
    () => chartRows.some((row) => row.assigned > 0 || row.completed > 0),
    [chartRows]
  );

  const xAxisProps = axisPropsForPeriod(period);

  const periodSelector = (
    <div className="ex-dash-trend-period" role="group" aria-label="Time span">
      {PTW_TREND_PERIOD_OPTIONS.map(({ value, label }) => (
        <button
          key={value}
          type="button"
          className={`ex-dash-trend-period-btn${
            period === value ? " ex-dash-trend-period-btn--active" : ""
          }`}
          disabled={loading}
          onClick={() => setPeriod(value)}
          aria-pressed={period === value}
        >
          {label}
        </button>
      ))}
    </div>
  );

  const openPermits = () => onNavigate?.("permits-submissions");

  if (loading) {
    return (
      <TrendShell
        subtitle={subtitle}
        periodSelector={periodSelector}
        variant="ex-dash-trend--loading"
        onChartClick={openPermits}
      >
        <button type="button" className="ptw-dash-chart__empty-action swi-muted" onClick={openPermits}>
          Loading trend… Click to open permits.
        </button>
      </TrendShell>
    );
  }

  if (loadError) {
    return (
      <TrendShell
        subtitle={subtitle}
        periodSelector={periodSelector}
        variant="ex-dash-trend--empty"
        onChartClick={openPermits}
      >
        <button type="button" className="ptw-dash-chart__empty-action swi-muted" onClick={openPermits}>
          {loadError}
        </button>
      </TrendShell>
    );
  }

  if (!hasPermits) {
    return (
      <TrendShell
        subtitle={subtitle}
        periodSelector={periodSelector}
        variant="ex-dash-trend--empty"
        onChartClick={openPermits}
      >
        <button type="button" className="ptw-dash-chart__empty-action swi-muted" onClick={openPermits}>
          No permits in this period — click to start a permit.
        </button>
      </TrendShell>
    );
  }

  return (
    <TrendShell
      subtitle={subtitle}
      periodSelector={periodSelector}
      onChartClick={openPermits}
    >
      <ResponsiveContainer width="100%" height={240}>
          <AreaChart data={chartRows} margin={{ top: 8, right: 8, left: 0, bottom: 4 }}>
            <defs>
              <linearGradient id="ptw-fill-created" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor={CREATED_STROKE} stopOpacity={0.28} />
                <stop offset="100%" stopColor={CREATED_STROKE} stopOpacity={0.02} />
              </linearGradient>
              <linearGradient id="ptw-fill-closed" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor={CLOSED_STROKE} stopOpacity={0.22} />
                <stop offset="100%" stopColor={CLOSED_STROKE} stopOpacity={0.02} />
              </linearGradient>
            </defs>
            <CartesianGrid
              strokeDasharray="4 8"
              stroke="rgba(148, 163, 184, 0.35)"
              vertical={false}
            />
            <XAxis
              dataKey="label"
              interval={0}
              {...xAxisProps}
              stroke="rgba(100, 116, 139, 0.5)"
              tickLine={false}
              axisLine={false}
            />
            <YAxis
              allowDecimals={false}
              tick={{ fontSize: 10, fill: "var(--ex-muted, #737373)" }}
              width={36}
              tickLine={false}
              axisLine={false}
            />
            <Tooltip
              contentStyle={{
                borderRadius: 12,
                border: "none",
                boxShadow: "0 8px 30px rgba(15, 23, 42, 0.12)",
                fontSize: 12
              }}
              labelStyle={{ fontWeight: 600 }}
              formatter={(value, name) => [
                value,
                name === "assigned" ? "Created" : "Closed"
              ]}
            />
            <Area
              type="monotone"
              dataKey="assigned"
              name="assigned"
              stroke={CREATED_STROKE}
              strokeWidth={2.5}
              fill="url(#ptw-fill-created)"
              dot={{ r: 0 }}
              activeDot={{ r: 5, strokeWidth: 0 }}
            />
            <Area
              type="monotone"
              dataKey="completed"
              name="completed"
              stroke={CLOSED_STROKE}
              strokeWidth={2.5}
              fill="url(#ptw-fill-closed)"
              dot={{ r: 0 }}
              activeDot={{ r: 5, strokeWidth: 0 }}
            />
          </AreaChart>
      </ResponsiveContainer>
    </TrendShell>
  );
}
