"use client";

import { useState, useEffect, useCallback } from "react";
import { TrendingUp, Loader2, Info, Zap } from "lucide-react";

interface Forecast {
  period: string;
  projectedReferrals: number;
  projectedConversions: number;
  projectedRevenue: number;
  confidence: string;
  assumptions: string[];
}

interface Scenario {
  label: string;
  adjustedRevenue: number;
  delta: number;
  description: string;
}

interface ForecastData {
  forecast: {
    forecasts: Forecast[];
    dataMonths: number;
    confidence: string;
    headline: string;
    caveat: string | null;
  };
  scenarios: Scenario[];
}

const CONFIDENCE_COLORS: Record<string, string> = {
  high: "text-emerald-600 bg-emerald-50",
  medium: "text-amber-600 bg-amber-50",
  low: "text-slate-500 bg-slate-100",
};

export function AiForecastSection({ brandId }: { brandId: string }) {
  const [data, setData] = useState<ForecastData | null>(null);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    if (!brandId) return;
    setLoading(true);
    try {
      const res = await fetch(`/api/ai-forecast?brandId=${brandId}`);
      if (res.ok) setData(await res.json());
    } catch { /* silent */ }
    setLoading(false);
  }, [brandId]);

  useEffect(() => { load(); }, [load]);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-5 h-5 text-brand-500 animate-spin" />
      </div>
    );
  }

  if (!data || data.forecast.forecasts.length === 0) {
    return (
      <div className="bg-white rounded-xl border border-slate-200 p-8 text-center">
        <TrendingUp className="w-8 h-8 text-slate-200 mx-auto mb-2" />
        <h3 className="text-sm font-bold text-slate-900 mb-1">AI Forecast</h3>
        <p className="text-xs text-slate-500 max-w-sm mx-auto">{data?.forecast.headline ?? "Not enough data for forecasting."}</p>
      </div>
    );
  }

  const { forecast, scenarios } = data;
  const maxRev = Math.max(...forecast.forecasts.map((f) => f.projectedRevenue), 1);
  const confColor = CONFIDENCE_COLORS[forecast.confidence] ?? CONFIDENCE_COLORS.low;

  return (
    <div className="space-y-4">
      {/* Headline */}
      <div className="bg-gradient-to-br from-blue-50 to-violet-50 rounded-xl border border-blue-200 p-5">
        <div className="flex items-start gap-3">
          <TrendingUp className="w-5 h-5 text-blue-600 shrink-0 mt-0.5" />
          <div>
            <p className="text-sm font-bold text-slate-800">{forecast.headline}</p>
            <div className="flex items-center gap-2 mt-1">
              <span className={`text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded ${confColor}`}>
                {forecast.confidence} confidence
              </span>
              <span className="text-[10px] text-slate-400">{forecast.dataMonths} months of data</span>
            </div>
            {forecast.caveat && (
              <p className="text-[11px] text-slate-500 mt-2 flex items-start gap-1">
                <Info className="w-3 h-3 text-slate-400 shrink-0 mt-0.5" />
                {forecast.caveat}
              </p>
            )}
          </div>
        </div>
      </div>

      {/* Projection chart */}
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-5 py-3.5 border-b border-slate-100">
          <h3 className="font-bold text-slate-800 text-sm">Revenue Projection</h3>
        </div>
        <div className="p-5">
          <div className="flex items-end gap-3 h-40">
            {forecast.forecasts.map((f) => {
              const height = Math.max((f.projectedRevenue / maxRev) * 100, 5);
              return (
                <div key={f.period} className="flex-1 flex flex-col items-center justify-end gap-1">
                  <span className="text-[9px] tabular-nums text-slate-400 font-semibold">
                    ${f.projectedRevenue >= 1000 ? `${Math.round(f.projectedRevenue / 1000)}k` : f.projectedRevenue}
                  </span>
                  <div
                    className="w-full bg-gradient-to-t from-blue-600 to-blue-300 rounded-t border-2 border-dashed border-blue-400"
                    style={{ height: `${height}%` }}
                  />
                  <span className="text-[9px] text-slate-400">{f.period.slice(0, 3)}</span>
                </div>
              );
            })}
          </div>
          {forecast.forecasts[0]?.assumptions && (
            <div className="mt-3 text-[10px] text-slate-400">
              <span className="font-semibold">Assumptions:</span> {forecast.forecasts[0].assumptions.join(" · ")}
            </div>
          )}
        </div>
      </div>

      {/* What-If Scenarios */}
      {scenarios.length > 0 && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2">
            <Zap className="w-4 h-4 text-amber-500" />
            <h3 className="font-bold text-slate-800 text-sm">What If Scenarios</h3>
          </div>
          <div className="divide-y divide-slate-100">
            {scenarios.map((s) => (
              <div key={s.label} className="px-5 py-3 flex items-center gap-4">
                <div className="flex-1">
                  <p className="text-sm font-semibold text-slate-800">{s.label}</p>
                  <p className="text-xs text-slate-500 mt-0.5">{s.description}</p>
                </div>
                <div className="text-right shrink-0">
                  <p className="text-sm font-bold text-emerald-600 tabular-nums">
                    +${(s.delta ?? 0).toLocaleString()}/mo
                  </p>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
