"use client";
import { useState } from "react";
import { TrendingUp, TrendingDown, Minus, ArrowUpRight, ArrowDownRight, Activity, Info, AlertTriangle } from "lucide-react";
import type { KpiItem } from "@/lib/services/analysis-schema";

const STATUS_BORDER: Record<string, string> = {
  good: "border-l-green-500",
  warning: "border-l-amber-500",
  critical: "border-l-red-500",
  neutral: "border-l-slate-300",
};
const STATUS_BG: Record<string, string> = {
  good: "",
  warning: "",
  critical: "",
  neutral: "",
};

const TREND_LABELS: Record<string, { text: string; cls: string; icon: typeof Activity }> = {
  improving: { text: "Improving",    cls: "text-green-600 bg-green-50",   icon: TrendingUp },
  declining: { text: "Declining",    cls: "text-red-500 bg-red-50",       icon: TrendingDown },
  stable:    { text: "Stable",       cls: "text-slate-500 bg-slate-50",   icon: Minus },
  volatile:  { text: "Volatile",     cls: "text-amber-600 bg-amber-50",   icon: Activity },
};

const CATEGORY_LABELS: Record<string, string> = {
  search:     "Search",
  engagement: "Engagement",
  conversion: "Conversion",
  technical:  "Technical",
};

/** Display safeguard — if the engine somehow produced an extreme value, cap it */
const DISPLAY_CAP = 1000;

function ChangeBadge({ change }: { change: NonNullable<KpiItem["change"]> }) {
  const isUp = change.direction === "up";
  const isDown = change.direction === "down";
  const cls = isUp ? "text-green-700 bg-green-50 border-green-200"
    : isDown ? "text-red-700 bg-red-50 border-red-200"
    : "text-slate-500 bg-slate-50 border-slate-200";
  const Icon = isUp ? ArrowUpRight : isDown ? ArrowDownRight : Minus;

  // "New" marker: engine sets label starting with "New" when previous period was 0
  const isNew = typeof change.label === "string" && change.label.trim().toLowerCase().startsWith("new");
  if (isNew) {
    return (
      <span className={`inline-flex items-center gap-0.5 text-[10px] font-bold rounded-md border px-1.5 py-0.5 text-green-700 bg-green-50 border-green-200`}>
        <Icon className="w-2.5 h-2.5" />
        New
      </span>
    );
  }

  // Display safeguard: cap extreme values to avoid "+282324%" leaking through
  let display = change.value;
  let prefix = "";
  if (display > DISPLAY_CAP) {
    display = DISPLAY_CAP;
    prefix = ">";
  } else if (display < -DISPLAY_CAP) {
    display = -DISPLAY_CAP;
    prefix = "<";
  } else if (display > 0) {
    prefix = "+";
  }

  return (
    <span className={`inline-flex items-center gap-0.5 text-[10px] font-bold rounded-md border px-1.5 py-0.5 ${cls}`}>
      <Icon className="w-2.5 h-2.5" />
      {prefix}{display}%
    </span>
  );
}

function KpiCard({ kpi }: { kpi: KpiItem }) {
  const [showCommentary, setShowCommentary] = useState(false);
  const trend = kpi.trend ? TREND_LABELS[kpi.trend] : null;

  // Compute data coverage percentage — suppress badges when insufficient
  const coverage = kpi.dataCoverage;
  const coveragePct = coverage ? (coverage.daysWithData / Math.max(coverage.totalDays, 1)) * 100 : 100;
  const insufficientData = coveragePct < 50;
  const veryLowData = coveragePct < 25;

  return (
    <div className={`bg-white rounded-xl border border-slate-200 border-l-4 ${STATUS_BORDER[kpi.status] ?? STATUS_BORDER.neutral} ${STATUS_BG[kpi.status] ?? ""} px-4 py-3 flex flex-col`}>
      {/* Label + category */}
      <div className="flex items-center justify-between gap-2">
        <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest truncate">{kpi.label}</p>
        {kpi.category && CATEGORY_LABELS[kpi.category] && (
          <span className="text-[8px] font-semibold text-slate-400 bg-slate-50 border border-slate-100 rounded-full px-1.5 py-0.5 shrink-0">
            {CATEGORY_LABELS[kpi.category]}
          </span>
        )}
      </div>

      {/* Value + change */}
      <div className="flex items-baseline gap-2 mt-1">
        <p className="text-2xl font-bold text-slate-900 leading-none">
          {kpi.value}
          {kpi.unit && <span className="text-sm font-normal text-slate-400 ml-0.5">{kpi.unit}</span>}
        </p>
        {insufficientData ? (
          <span className="inline-flex items-center gap-0.5 text-[10px] font-bold rounded-md border px-1.5 py-0.5 text-slate-500 bg-slate-50 border-slate-200">New data</span>
        ) : kpi.change ? <ChangeBadge change={kpi.change} /> : null}
      </div>

      {/* Previous value + YoY — hide when coverage is very low */}
      <div className="flex items-center gap-2 mt-1.5 flex-wrap text-[10px]">
        {!veryLowData && kpi.previousValue && (
          <span className="text-slate-400">
            Previous: <span className="font-medium text-slate-500">{kpi.previousValue}</span>
          </span>
        )}
        {kpi.yoyChange && (() => {
          const isNew = typeof kpi.yoyChange.label === "string" && kpi.yoyChange.label.trim().toLowerCase().startsWith("new");
          let v = kpi.yoyChange.value;
          let prefix = "";
          if (!isNew) {
            if (v > DISPLAY_CAP) { v = DISPLAY_CAP; prefix = ">"; }
            else if (v < -DISPLAY_CAP) { v = -DISPLAY_CAP; prefix = "<"; }
            else if (v > 0) prefix = "+";
          }
          return (
            <span className="text-slate-400">
              YoY: <span className={`font-semibold ${kpi.yoyChange.direction === "up" ? "text-green-600" : kpi.yoyChange.direction === "down" ? "text-red-500" : "text-slate-500"}`}>
                {isNew ? "New" : `${prefix}${v}%`}
              </span>
            </span>
          );
        })()}
      </div>

      {/* Trend + source */}
      <div className="flex items-center justify-between gap-2 mt-2 pt-2 border-t border-slate-50">
        {trend ? (
          <span className={`inline-flex items-center gap-1 text-[9px] font-semibold rounded-full px-1.5 py-0.5 ${trend.cls}`}>
            <trend.icon className="w-2.5 h-2.5" />
            {trend.text}
          </span>
        ) : <span />}
        <span className="text-[9px] text-slate-300 font-medium">{kpi.source}</span>
      </div>

      {/* Commentary (expandable) */}
      {kpi.commentary && (
        <button
          type="button"
          onClick={() => setShowCommentary(v => !v)}
          className="flex items-center gap-1 mt-1.5 text-[9px] font-semibold text-brand-600 hover:text-brand-700 self-start"
          title={showCommentary ? "Hide analysis" : "Show analysis"}
        >
          <Info className="w-2.5 h-2.5" />
          {showCommentary ? "Hide analysis" : "Why this matters"}
        </button>
      )}
      {kpi.commentary && showCommentary && (
        <p className="text-[10px] text-slate-500 leading-relaxed mt-1.5 bg-slate-50 rounded px-2 py-1.5 border border-slate-100">
          {kpi.commentary}
        </p>
      )}
    </div>
  );
}

export function KpiCards({ kpis, periodLabel }: { kpis: KpiItem[]; periodLabel?: string }) {
  // Suppress Bounce Rate from the UI. The analysis engine still emits it
  // (GA4 provides the number) but brands on site-tag-only tracking see
  // 0.0% and it's a metric users specifically don't want surfaced. We
  // filter at the display layer so the raw analysis object stays intact
  // for exports, AI context, and API consumers.
  const visibleKpis = kpis.filter((k) => !/bounce\s*rate/i.test(k.label));

  // Group by category if any KPI has a category
  const hasCategories = visibleKpis.some(k => k.category);
  const order: Array<"search" | "engagement" | "conversion" | "technical"> = ["search", "engagement", "conversion", "technical"];
  const grouped = hasCategories
    ? order.map(cat => ({ category: cat, items: visibleKpis.filter(k => k.category === cat) })).filter(g => g.items.length > 0)
    : [{ category: "all" as const, items: visibleKpis }];
  const uncategorized = hasCategories ? visibleKpis.filter(k => !k.category) : [];

  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      <div className="px-4 py-2.5 border-b border-slate-100 flex items-center justify-between">
        <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Key Performance Indicators</p>
        {periodLabel && <span className="text-[10px] text-slate-300">{periodLabel}</span>}
      </div>
      <div className="p-4 space-y-4">
        {grouped.map(group => (
          <div key={group.category}>
            {hasCategories && group.category !== "all" && CATEGORY_LABELS[group.category as string] && (
              <p className="text-[9px] font-bold uppercase tracking-widest text-slate-400 mb-2">
                {CATEGORY_LABELS[group.category as string]}
              </p>
            )}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
              {group.items.map((kpi, i) => <KpiCard key={`${group.category}-${i}`} kpi={kpi} />)}
            </div>
          </div>
        ))}
        {uncategorized.length > 0 && (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
            {uncategorized.map((kpi, i) => <KpiCard key={`uncat-${i}`} kpi={kpi} />)}
          </div>
        )}
      </div>
    </div>
  );
}
