"use client";

import { useState, useMemo } from "react";
import { BarChart3, AlertTriangle, Eye, EyeOff } from "lucide-react";
import type { ChartSpec } from "@/lib/services/analysis-schema";
import {
  ResponsiveContainer,
  LineChart, Line,
  BarChart, Bar,
  ComposedChart,
  AreaChart, Area,
  XAxis, YAxis,
  CartesianGrid,
  Tooltip, Legend,
  ReferenceLine,
} from "recharts";

function fmtDate(d: string): string {
  if (!d || d === "undefined" || d === "null") return d;
  // Handle "Week 1", "Week of 2026-01-01", or non-date strings
  if (!/^\d{4}/.test(d) && !/^\w{3}\s\d/.test(d)) return d;
  try {
    const parsed = new Date(d);
    if (isNaN(parsed.getTime())) return d;
    return parsed.toLocaleDateString("en-US", { month: "short", day: "numeric" });
  } catch { return d; }
}

function fmtNum(v: unknown): string {
  if (typeof v === "number") return v.toLocaleString();
  return String(v ?? "");
}

function CustomTooltip({ active, payload, label }: { active?: boolean; payload?: Array<{ name: string; value: number; color: string }>; label?: string }) {
  if (!active || !payload?.length) return null;
  return (
    <div className="bg-[#0f172a] rounded-lg px-3 py-2.5 shadow-xl text-[11px] max-w-xs" style={{ border: "none" }}>
      <p className="text-slate-300 font-semibold mb-1.5">{fmtDate(String(label))}</p>
      {payload.map((p, i) => (
        <div key={i} className="flex items-center gap-2 py-0.5">
          <span className="w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: p.color }} />
          <span className="text-slate-400">{p.name}:</span>
          <span className="text-white font-semibold">{fmtNum(p.value)}</span>
        </div>
      ))}
    </div>
  );
}

function shortPath(url: string): string {
  try {
    const p = new URL(url).pathname.replace(/\/$/, "");
    const seg = p.split("/").filter(Boolean);
    return seg.length > 0 ? seg[seg.length - 1].replace(/-/g, " ").slice(0, 28) : "/";
  } catch { return url.slice(0, 28); }
}

export function ChartSection({ chart }: { chart: ChartSpec }) {
  const [hiddenAxes, setHiddenAxes] = useState<Set<string>>(new Set());
  const [showAnnotations, setShowAnnotations] = useState(true);

  const data = useMemo(() => {
    return chart.data.map(row => {
      const out: Record<string, string | number> = { ...row };
      for (const axis of chart.yAxes) {
        const v = row[axis.key];
        out[axis.key] = typeof v === "number" ? v : Number(v ?? 0);
      }
      return out;
    });
  }, [chart.data, chart.yAxes]);

  // Hide "previous" axes if all zeros (no comparison data available)
  const prevAxes = chart.yAxes.filter(a => a.key === "previous" || a.label.toLowerCase().includes("previous"));
  const prevAllZero = prevAxes.length > 0 && data.every(d => prevAxes.every(a => (d[a.key] as number) === 0));
  const effectiveYAxes = prevAllZero ? chart.yAxes.filter(a => !prevAxes.includes(a)) : chart.yAxes;
  const visibleAxes = effectiveYAxes.filter(a => !hiddenAxes.has(a.key));
  const hasAnnotations = chart.annotations && chart.annotations.length > 0;
  const isTopPages = chart.id === "chart_top_pages";

  function toggleAxis(key: string) {
    setHiddenAxes(prev => {
      const next = new Set(prev);
      if (next.has(key)) next.delete(key); else next.add(key);
      if (next.size >= effectiveYAxes.length) return prev;
      return next;
    });
  }

  if (data.length === 0) {
    return (
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-4 py-3 border-b border-slate-100 flex items-center gap-2">
          <BarChart3 className="w-3.5 h-3.5 text-slate-400" />
          <h3 className="text-sm font-bold text-slate-800">{chart.title}</h3>
        </div>
        <div className="px-4 py-10 text-center">
          <AlertTriangle className="w-5 h-5 text-slate-300 mx-auto mb-2" />
          <p className="text-xs text-slate-400">No data available for this chart</p>
        </div>
      </div>
    );
  }

  const limitedData = data.length < 5;
  const firstDate = data[0]?.[chart.xAxis.key] ? fmtDate(String(data[0][chart.xAxis.key])) : null;
  const lastDate = data[data.length - 1]?.[chart.xAxis.key] ? fmtDate(String(data[data.length - 1][chart.xAxis.key])) : null;

  function renderChart() {
    const xKey = chart.xAxis.key;
    const commonProps = { data, margin: { top: 20, right: 16, left: 0, bottom: isTopPages ? 60 : 0 } };

    const annotationElements = showAnnotations && chart.annotations
      ? chart.annotations.map((ann, i) => (
          <ReferenceLine key={`ann-${i}`} x={ann.x} stroke={ann.color} strokeDasharray="4 2" strokeOpacity={0.4}
            label={{ value: ann.label, position: i % 2 === 0 ? "top" : "insideTopRight", fill: ann.color, fontSize: 11, fontWeight: 700,
              style: { textShadow: "0 0 6px rgba(255,255,255,1), 0 0 12px rgba(255,255,255,0.8), 0 1px 2px rgba(0,0,0,0.15)" } }} />
        ))
      : null;

    const axes = (
      <>
        <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" strokeOpacity={0.5} vertical={false} />
        <XAxis dataKey={xKey} stroke="#94a3b8" tick={{ fontSize: 10, fill: "#94a3b8" }} tickLine={false}
          axisLine={{ stroke: "#e2e8f0" }} minTickGap={isTopPages ? 0 : 20}
          tickFormatter={isTopPages ? shortPath : fmtDate}
          angle={isTopPages ? -35 : 0} textAnchor={isTopPages ? "end" : "middle"} height={isTopPages ? 80 : 30} />
        <YAxis stroke="#94a3b8" tick={{ fontSize: 10, fill: "#94a3b8" }} tickLine={false} axisLine={false} width={48}
          tickFormatter={(v) => { if (typeof v !== "number") return String(v); if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)}M`; if (v >= 1_000) return `${(v / 1_000).toFixed(1)}k`; return v.toString(); }} />
        <Tooltip content={<CustomTooltip />} cursor={{ fill: "#3b82f610", stroke: "#3b82f6", strokeDasharray: "3 3" }} />
        <Legend iconType="circle" wrapperStyle={{ fontSize: 11, paddingTop: 8 }} formatter={(value) => <span className="text-slate-600">{value}</span>} />
      </>
    );

    if (chart.type === "line") {
      return (<LineChart {...commonProps}>{axes}{visibleAxes.map(axis => (
        <Line key={axis.key} type="monotone" dataKey={axis.key} name={axis.label} stroke={axis.color} strokeWidth={2.5}
          dot={data.length <= 20 ? { r: 2.5, fill: axis.color, strokeWidth: 0 } : false} activeDot={{ r: 5, strokeWidth: 2, stroke: "#fff" }} isAnimationActive animationDuration={600} />
      ))}{annotationElements}</LineChart>);
    }
    if (chart.type === "area") {
      return (<AreaChart {...commonProps}>{axes}
        <defs>{visibleAxes.map(axis => (
          <linearGradient key={axis.key} id={`grad_${axis.key}`} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={axis.color} stopOpacity={0.25} />
            <stop offset="100%" stopColor={axis.color} stopOpacity={0.02} />
          </linearGradient>
        ))}</defs>
        {visibleAxes.map(axis => (
          <Area key={axis.key} type="monotone" dataKey={axis.key} name={axis.label} stroke={axis.color} fill={`url(#grad_${axis.key})`} strokeWidth={2.5} isAnimationActive animationDuration={600} />
        ))}{annotationElements}</AreaChart>);
    }
    if (chart.type === "composed") {
      return (<ComposedChart {...commonProps}>{axes}
        <defs>{visibleAxes.filter(a => a.type !== "line").map(axis => (
          <linearGradient key={axis.key} id={`grad_${axis.key}`} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={axis.color} stopOpacity={0.85} />
            <stop offset="100%" stopColor={axis.color} stopOpacity={0.45} />
          </linearGradient>
        ))}</defs>
        {visibleAxes.map(axis =>
          axis.type === "line"
            ? <Line key={axis.key} type="monotone" dataKey={axis.key} name={axis.label} stroke={axis.color} strokeWidth={2.5}
                dot={data.length <= 20 ? { r: 2.5, fill: axis.color, strokeWidth: 0 } : false} activeDot={{ r: 5, strokeWidth: 2, stroke: "#fff" }} isAnimationActive animationDuration={600} />
            : <Bar key={axis.key} dataKey={axis.key} name={axis.label} fill={`url(#grad_${axis.key})`} radius={[4, 4, 0, 0]} isAnimationActive animationDuration={600} />
        )}{annotationElements}</ComposedChart>);
    }
    return (<BarChart {...commonProps}>{axes}
      <defs>{visibleAxes.map(axis => (
        <linearGradient key={axis.key} id={`grad_${axis.key}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={axis.color} stopOpacity={0.85} />
          <stop offset="100%" stopColor={axis.color} stopOpacity={0.5} />
        </linearGradient>
      ))}</defs>
      {visibleAxes.map(axis => (
        <Bar key={axis.key} dataKey={axis.key} name={axis.label} fill={`url(#grad_${axis.key})`} radius={[4, 4, 0, 0]} isAnimationActive animationDuration={600} />
      ))}{annotationElements}</BarChart>);
  }

  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      <div className="px-4 py-3 border-b border-slate-100 flex items-center gap-2 flex-wrap">
        <BarChart3 className="w-3.5 h-3.5 text-brand-600" />
        <div className="min-w-0 flex-1">
          <h3 className="text-sm font-bold text-slate-800 truncate">{chart.title}</h3>
          {chart.subtitle && <p className="text-[10px] text-slate-400 mt-0.5">{chart.subtitle}</p>}
        </div>
        <div className="flex items-center gap-1.5 flex-wrap">
          {hasAnnotations && (
            <button onClick={() => setShowAnnotations(!showAnnotations)}
              className={`flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-medium transition-colors ${showAnnotations ? "bg-red-50 text-red-600 border border-red-200" : "bg-slate-50 text-slate-400 border border-slate-200"}`}>
              Events {showAnnotations ? "On" : "Off"}
            </button>
          )}
          {effectiveYAxes.length >= 2 && (
            <div className="flex items-center gap-1">
              {effectiveYAxes.map(axis => {
                const isHidden = hiddenAxes.has(axis.key);
                return (
                  <button key={axis.key} onClick={() => toggleAxis(axis.key)}
                    className={`flex items-center gap-1 text-[10px] px-2 py-0.5 rounded border transition-colors ${isHidden ? "text-slate-300 border-slate-100 bg-slate-50" : "text-slate-600 border-slate-200 hover:bg-slate-50"}`}>
                    <span className="w-1.5 h-1.5 rounded-full shrink-0" style={{ backgroundColor: isHidden ? "#cbd5e1" : axis.color }} />
                    {axis.label}
                    {isHidden ? <EyeOff className="w-2.5 h-2.5 text-slate-300" /> : <Eye className="w-2.5 h-2.5 text-slate-400" />}
                  </button>
                );
              })}
            </div>
          )}
          <span className="text-[10px] font-medium text-slate-400 bg-slate-50 px-2 py-0.5 rounded shrink-0">{chart.source}</span>
        </div>
      </div>

      {limitedData && (
        <div className="px-4 py-1.5 bg-amber-50 border-b border-amber-100 flex items-center gap-2">
          <AlertTriangle className="w-3 h-3 text-amber-500 shrink-0" />
          <p className="text-[10px] text-amber-600">Limited data ({data.length} point{data.length !== 1 ? "s" : ""}) — chart may not reflect meaningful trends yet</p>
        </div>
      )}
      {prevAllZero && (
        <div className="px-4 py-1.5 bg-slate-50 border-b border-slate-100">
          <p className="text-[10px] text-slate-400">Previous period data not available — comparison hidden</p>
        </div>
      )}

      <div className="px-2 py-4">
        <ResponsiveContainer width="100%" height={300}>
          {renderChart()}
        </ResponsiveContainer>
        {firstDate && lastDate && (
          <p className="text-[10px] text-slate-400 text-right px-2 mt-1">{data.length} data points · {firstDate} – {lastDate}</p>
        )}
      </div>
    </div>
  );
}
