"use client";

import React from "react";
import { yAxisTickFormatter } from "./theme";
import type { Insight } from "../../analysis/insight";
import { pinInsight } from "@/lib/evolution/history.pins";

type Props = {
  insight?: Insight | null;
  onClose?: () => void;
};

export const InsightPanel: React.FC<Props> = ({ insight, onClose }) => {
  if (!insight) {
    return (
      <div className="rounded-xl border border-[hsl(var(--border))/60] bg-[hsl(var(--card))/80] p-4 text-sm text-[hsl(var(--muted-foreground))]">
        Select a point on the chart to see insights.
      </div>
    );
  }

  const {
    point,
    prev,
    next,
    rolling,
    badges,
    stabilityWindow,
    surgeDelta,
    predictedNext,
  } = insight;

  const badgeStyle: Record<string, string> = {
    STABILITY: "bg-emerald-500/15 text-emerald-300 border-emerald-400/30",
    SURGE: "bg-orange-500/15 text-orange-300 border-orange-400/30",
    PREDICTION: "bg-sky-500/15 text-sky-300 border-sky-400/30",
    BASELINE: "bg-zinc-500/10 text-zinc-300 border-zinc-400/20",
  };

  // 📌 زر التثبيت
  const handlePin = () => {
    pinInsight({
      timestamp: new Date(point.timestamp).toISOString(),
      trend: yAxisTickFormatter(point.trendValue),
      confidence: point.confidence,
      note: `Insight pinned (${yAxisTickFormatter(point.trendValue)})`,
    });
    alert("📌 Insight pinned successfully to Evolution Logs!");
  };

  return (
    <div className="rounded-2xl border border-[hsl(var(--border))/60] bg-[hsl(var(--card))/90] p-4 shadow-lg">
      {/* 🧭 Header */}
      <div className="flex items-center justify-between mb-3">
        <h3 className="text-[hsl(var(--primary))] font-semibold tracking-wide">
          Insight
        </h3>
        <div className="flex gap-2">
          <button
            onClick={handlePin}
            className="text-xs px-2 py-1 rounded border border-[hsl(var(--border))/60] hover:bg-white/5"
          >
            📌 Pin
          </button>
          {onClose && (
            <button
              onClick={onClose}
              className="text-xs px-2 py-1 rounded border border-[hsl(var(--border))/60] hover:bg-white/5"
            >
              Close
            </button>
          )}
        </div>
      </div>

      {/* 🏷️ Badges */}
      <div className="flex flex-wrap gap-2 mb-3">
        {badges.map((b, i) => (
          <span
            key={i}
            className={`text-[10px] px-2 py-0.5 rounded border ${badgeStyle[b]}`}
          >
            {b}
          </span>
        ))}
      </div>

      {/* 🧮 Core Info */}
      <div className="grid grid-cols-2 gap-3 text-sm">
        <div>
          <div className="text-xs opacity-70">Timestamp</div>
          <div>{new Date(point.timestamp).toLocaleString()}</div>
        </div>
        <div>
          <div className="text-xs opacity-70">Trend</div>
          <div>{yAxisTickFormatter(point.trendValue)}</div>
        </div>
        <div>
          <div className="text-xs opacity-70">Confidence</div>
          <div>{(point.confidence * 100).toFixed(1)}%</div>
        </div>
        <div>
          <div className="text-xs opacity-70">Δ Change Rate</div>
          <div>{(point.changeRate ?? 0).toFixed(2)}%</div>
        </div>
      </div>

      {point?.notes && (
        <div className="mt-3 text-xs opacity-80 italic">
          Notes: {point.notes}
        </div>
      )}

      <hr className="my-3 border-[hsl(var(--border))/40]" />

      {/* 📊 Rolling Stats */}
      <div className="grid grid-cols-2 gap-3 text-sm">
        <div>
          <div className="text-xs opacity-70">Rolling Window</div>
          <div>{rolling.window} pts</div>
        </div>
        <div>
          <div className="text-xs opacity-70">Avg Confidence</div>
          <div>{(rolling.avgConfidence * 100).toFixed(1)}%</div>
        </div>
        <div>
          <div className="text-xs opacity-70">Avg Change Rate</div>
          <div>{rolling.avgChangeRate.toFixed(2)}%</div>
        </div>
        {stabilityWindow && (
          <div className="col-span-2">
            <div className="text-xs opacity-70">Stability Window</div>
            <div>
              {new Date(stabilityWindow.start).toLocaleString()} →{" "}
              {new Date(stabilityWindow.end).toLocaleString()}
            </div>
          </div>
        )}
      </div>

      {/* ⚡ Surge */}
      {typeof surgeDelta === "number" && (
        <div className="mt-3 text-sm">
          <div className="text-xs opacity-70">Confidence Surge</div>
          <div
            className={surgeDelta > 0 ? "text-emerald-300" : "text-rose-300"}
          >
            {surgeDelta > 0 ? "▲" : "▼"}{" "}
            {Math.abs(surgeDelta * 100).toFixed(1)}%
          </div>
        </div>
      )}

      {/* 🔮 Predicted */}
      {predictedNext && (
        <>
          <hr className="my-3 border-[hsl(var(--border))/40]" />
          <div className="text-xs opacity-70 mb-1">Predicted Next</div>
          <div className="grid grid-cols-2 gap-3 text-sm">
            <div>
              <div className="text-xs opacity-70">Time</div>
              <div>{new Date(predictedNext.timestamp).toLocaleString()}</div>
            </div>
            <div>
              <div className="text-xs opacity-70">Trend</div>
              <div>{yAxisTickFormatter(predictedNext.trendValue)}</div>
            </div>
            <div>
              <div className="text-xs opacity-70">Confidence</div>
              <div>{(predictedNext.confidence * 100).toFixed(1)}%</div>
            </div>
          </div>
        </>
      )}

      {/* ⏮ Navigation */}
      {(prev || next) && (
        <div className="mt-3 flex justify-between text-xs opacity-80">
          <div>
            {prev
              ? `Prev: ${new Date(prev.timestamp).toLocaleTimeString()}`
              : ""}
          </div>
          <div>
            {next
              ? `Next: ${new Date(next.timestamp).toLocaleTimeString()}`
              : ""}
          </div>
        </div>
      )}
    </div>
  );
};
