import React from "react";
import { useNavigate } from "react-router-dom";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Cell,
} from "recharts";
import { useTheme } from "../../../../contexts/ThemeContext";
import AddToPersonalizedButton from "../common/AddToPersonalizedButton";
import "../styles/ObservationsOpenClosedBarChart.css";

const OBS_TIME_OPTIONS = [
  { value: "all", label: "All time" },
  { value: "7d", label: "Last 7 days" },
  { value: "30d", label: "Last 30 days" },
  { value: "90d", label: "Last 90 days" },
];

const DEFAULT_DATA = [
  { name: "Open", count: 0, key: "open" },
  { name: "Closed", count: 0, key: "closed" },
];

const COLORS = { open: "#f21b23", closed: "#10b981" };

const CustomTooltip = ({ active, payload }) => {
  if (!active || !payload?.length) return null;
  const value = payload[0]?.value ?? 0;
  const name = payload[0]?.payload?.name ?? "";
  return (
    <div className="obs-oc-tooltip">
      <div className="obs-oc-tooltip-label">{name} observations</div>
      <div className="obs-oc-tooltip-value">{value}</div>
      <div className="obs-oc-tooltip-hint">Click chart to view list</div>
    </div>
  );
};

const ObservationsOpenClosedBarChart = ({ data, timePeriod = "all", onTimePeriodChange }) => {
  const navigate = useNavigate();
  const { theme } = useTheme();
  const isDark = theme === "night";
  const chartData = (data && data.length) ? data : DEFAULT_DATA;

  const gridStroke = isDark ? "rgba(255,255,255,0.15)" : "rgba(0,0,0,0.06)";
  const axisStroke = isDark ? "rgba(255,255,255,0.35)" : "#e2e8f0";
  const tickFill = isDark ? "rgba(255,255,255,0.9)" : "#64748b";
  const cursorFill = isDark ? "rgba(255,255,255,0.06)" : "rgba(15, 23, 42, 0.04)";

  const listUrl = timePeriod && timePeriod !== "all"
    ? `/dashboard/observations-open-closed-page?period=${encodeURIComponent(timePeriod)}`
    : "/dashboard/observations-open-closed-page";

  return (
    <div
      className="obs-oc-bar-container chart-card chart-card--has-add-btn obs-oc-bar-premium"
      role="button"
      tabIndex={0}
      onClick={() => navigate(listUrl)}
      onKeyDown={(e) => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          navigate(listUrl);
        }
      }}
      aria-label="Observations open vs closed bar chart. Click to view full list."
    >
      <AddToPersonalizedButton widgetId="observationsOpenClosed" />
      <div className="obs-oc-bar-header">
        <div className="obs-oc-bar-title-wrap">
          <span className="obs-oc-bar-icon" aria-hidden>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="10" />
              <path d="M12 6v6l4 2" />
            </svg>
          </span>
          <h2 className="obs-oc-bar-title">Observations: Open vs Closed</h2>
        </div>
        <p className="obs-oc-bar-subtitle">
          Opening observations without a closing form = Open; with a closing form linked = Closed.
        </p>
      </div>
      {onTimePeriodChange && (
        <div
          className="obs-oc-bar-time-filter"
          onClick={(e) => e.stopPropagation()}
          onKeyDown={(e) => e.stopPropagation()}
          role="presentation"
        >
          <label htmlFor="obs-oc-time-period" className="obs-oc-bar-time-filter-label">Time period</label>
          <select
            id="obs-oc-time-period"
            value={timePeriod}
            onChange={(e) => onTimePeriodChange(e.target.value)}
            className="obs-oc-bar-time-select"
            aria-label="Filter observations by time period"
          >
            {OBS_TIME_OPTIONS.map(({ value, label }) => (
              <option key={value} value={value}>{label}</option>
            ))}
          </select>
        </div>
      )}
      <div className="obs-oc-bar-chart-wrap">
        <ResponsiveContainer width="100%" height={260}>
          <BarChart
            data={chartData}
            margin={{ top: 16, right: 20, left: 12, bottom: 12 }}
          >
            <CartesianGrid strokeDasharray="0" stroke={gridStroke} vertical={false} />
            <XAxis
              dataKey="name"
              tick={{ fontSize: 13, fontWeight: 600, fill: tickFill }}
              axisLine={{ stroke: axisStroke, strokeWidth: 1.5 }}
              tickLine={false}
              tickMargin={10}
            />
            <YAxis
              type="number"
              tick={{ fontSize: 12, fill: tickFill }}
              axisLine={false}
              tickLine={false}
              allowDecimals={false}
              tickMargin={8}
              width={32}
            />
            <Tooltip
              content={<CustomTooltip />}
              cursor={{ fill: cursorFill, radius: 6 }}
            />
            <Bar dataKey="count" name="Observations" radius={[8, 8, 0, 0]} maxBarSize={80}>
              {chartData.map((entry) => (
                <Cell
                  key={entry.key || entry.name}
                  fill={COLORS[entry.key] || "#94a3b8"}
                />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
};

export default ObservationsOpenClosedBarChart;
