"use client";
import { TrendingUp, Calendar, AlertTriangle, Target, ArrowUpRight, ArrowDownRight, Minus } from "lucide-react";
import type { Prediction } from "@/lib/services/analysis-schema";
import { InlineActions } from "./inline-actions";

const CONFIDENCE_BADGE: Record<string, string> = {
  high:   "bg-green-50 text-green-700 border-green-200",
  medium: "bg-amber-50 text-amber-700 border-amber-200",
  low:    "bg-slate-100 text-slate-500 border-slate-200",
};

// Prediction type → icon + theme
const TYPE_CFG: Record<string, { icon: typeof TrendingUp; iconCls: string; headerCls: string }> = {
  trajectory:  { icon: TrendingUp,    iconCls: "text-blue-600 bg-blue-50 border-blue-200",       headerCls: "bg-blue-50/50" },
  seasonal:    { icon: Calendar,      iconCls: "text-purple-600 bg-purple-50 border-purple-200", headerCls: "bg-purple-50/50" },
  risk:        { icon: AlertTriangle, iconCls: "text-red-600 bg-red-50 border-red-200",          headerCls: "bg-red-50/50" },
  opportunity: { icon: Target,        iconCls: "text-green-600 bg-green-50 border-green-200",    headerCls: "bg-green-50/50" },
};

/** Classify outlook string into positive / negative / neutral for badge colouring */
function outlookVariant(outlook: string | undefined, fallbackDir: "up" | "down" | "flat"): "positive" | "negative" | "neutral" {
  if (!outlook) return fallbackDir === "up" ? "positive" : fallbackDir === "down" ? "negative" : "neutral";
  const lower = outlook.toLowerCase();
  if (/risk|decline|contraction|headwind|down|weak/.test(lower)) return "negative";
  if (/growth|uplift|momentum|strong|growing|stable|on track/.test(lower)) return "positive";
  return "neutral";
}
const OUTLOOK_BADGE: Record<string, string> = {
  positive: "bg-green-50 text-green-700 border-green-200",
  negative: "bg-red-50 text-red-700 border-red-200",
  neutral:  "bg-slate-50 text-slate-600 border-slate-200",
};

function PredictionCard({ p, brandId }: { p: Prediction; brandId?: string }) {
  const typeCfg = p.predictionType ? (TYPE_CFG[p.predictionType] ?? TYPE_CFG.trajectory) : TYPE_CFG.trajectory;
  const TypeIcon = typeCfg.icon;

  const delta = p.predicted - p.current;
  const pct = p.current > 0 ? Math.round((delta / p.current) * 100) : 0;
  const direction: "up" | "down" | "flat" = delta > 0 ? "up" : delta < 0 ? "down" : "flat";
  const DirectionIcon = direction === "up" ? ArrowUpRight : direction === "down" ? ArrowDownRight : Minus;
  const directionCls = direction === "up" ? "text-green-600" : direction === "down" ? "text-red-500" : "text-slate-400";

  const variant = outlookVariant(p.outlook, direction);
  const outlookCls = OUTLOOK_BADGE[variant];

  return (
    <div className="rounded-xl bg-white border border-slate-200 overflow-hidden">
      {/* Header */}
      <div className={`px-4 py-2.5 border-b border-slate-100 flex items-center gap-2 ${typeCfg.headerCls}`}>
        <div className={`w-6 h-6 rounded-md border flex items-center justify-center shrink-0 ${typeCfg.iconCls}`}>
          <TypeIcon className="w-3.5 h-3.5" />
        </div>
        <div className="min-w-0 flex-1">
          <p className="text-[10px] font-bold uppercase tracking-widest text-slate-500">{p.timeframe}</p>
          <p className="text-xs font-bold text-slate-800 truncate">{p.metric}</p>
        </div>
        {p.outlook && (
          <span className={`text-[9px] font-bold uppercase rounded-full border px-2 py-0.5 shrink-0 ${outlookCls}`}>
            {p.outlook}
          </span>
        )}
      </div>

      {/* Body */}
      <div className="px-4 py-3">
        {/* Predicted vs current */}
        <div className="flex items-baseline gap-2 flex-wrap">
          <p className="text-2xl font-bold text-slate-900 leading-none">{p.predicted.toLocaleString()}</p>
          <span className={`inline-flex items-center gap-0.5 text-xs font-bold ${directionCls}`}>
            <DirectionIcon className="w-3 h-3" />
            {pct > 0 ? "+" : ""}{pct}%
          </span>
        </div>
        <p className="text-[10px] text-slate-400 mt-0.5">
          from {p.current.toLocaleString()} current
        </p>

        {/* Confidence */}
        <div className="flex items-center gap-1.5 mt-2">
          <span className={`text-[9px] font-semibold rounded-full border px-1.5 py-0.5 ${CONFIDENCE_BADGE[p.confidence] ?? CONFIDENCE_BADGE.low}`}>
            {p.confidence} confidence
          </span>
        </div>

        {/* Basis */}
        <p className="text-[10px] text-slate-500 mt-2 leading-relaxed">
          <span className="font-semibold text-slate-600">Basis:</span> {p.basis}
        </p>

        {/* Caveat */}
        {p.caveat && (
          <div className="mt-2 rounded-md border border-amber-100 bg-amber-50 px-2 py-1.5">
            <p className="text-[10px] text-amber-700 leading-relaxed italic">
              <span className="font-semibold not-italic">Caveat:</span> {p.caveat}
            </p>
          </div>
        )}

        {brandId && direction === "down" && (
          <InlineActions
            brandId={brandId}
            itemId={`pred_${p.metric.replace(/\s+/g, "_").toLowerCase()}`}
            title={`Monitor: ${p.metric} projected to decline`}
            description={`${p.metric} projected from ${p.current.toLocaleString()} to ${p.predicted.toLocaleString()} over ${p.timeframe}`}
            priority="medium"
            evidence={p.basis}
            actionable={true}
          />
        )}
      </div>
    </div>
  );
}

export function PredictionsSection({ predictions, brandId }: { predictions: Prediction[]; brandId?: string }) {
  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">
        <TrendingUp className="w-3.5 h-3.5 text-blue-600" />
        <h3 className="text-sm font-bold text-slate-800">Outlook & Predictions</h3>
        <span className="ml-auto text-[10px] text-slate-400">{predictions.length} forecast{predictions.length === 1 ? "" : "s"}</span>
      </div>
      <div className="p-3 grid grid-cols-1 md:grid-cols-2 gap-2.5">
        {predictions.map((p, i) => (
          <PredictionCard key={i} p={p} brandId={brandId} />
        ))}
      </div>
    </div>
  );
}
