"use client";

import { useState, useEffect, useCallback } from "react";
import { useBrand } from "@/context/brand-context";
import {
  DollarSign, TrendingUp, Target, Zap, ArrowDown,
  BarChart3, Loader2, Download,
} from "lucide-react";
import { nfmt, safeLen } from "@/lib/utils";

interface RoiData {
  headline: {
    totalRevenue: number;
    totalConversions: number;
    roiMultiplier: number;
    revenueGrowth: number;
    conversionGrowth: number;
  };
  channelRevenue: Array<{ channel: string; revenue: number; conversions: number }>;
  funnel: {
    citationsDetected: number;
    referralClicks: number;
    engagedVisitors: number;
    engagementRate: number;
    conversions: number;
    qualifiedLeads: number;
    qualificationRate: number;
    closedRevenue: number;
  };
  monthlyTrend: Array<{
    month: string;
    totalRevenue: number;
    llmoRevenue: number;
    geoRevenue: number;
    aeoRevenue: number;
    conversions: number;
    referrals: number;
  }>;
  topPages: Array<{ page: string; conversions: number; revenue: number }>;
  costAnalysis: {
    subscriptionCost: number;
    aiCreditsUsed: number;
    totalInvestment: number;
    totalRevenue: number;
    roi: number;
    paybackDays: number | null;
  };
}

const CHANNEL_LABELS: Record<string, string> = {
  llmo: "LLMO", geo: "GEO", aeo: "AEO", assisted: "Assisted",
};

const CHANNEL_COLORS: Record<string, string> = {
  llmo: "bg-violet-500", geo: "bg-blue-500", aeo: "bg-amber-500", assisted: "bg-emerald-500",
};

export default function AiRoiPage() {
  const { brand } = useBrand();
  const [data, setData] = useState<RoiData | null>(null);
  const [loading, setLoading] = useState(true);
  const [range, setRange] = useState("90d");

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

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

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

  if (!data || (data.headline?.totalConversions ?? 0) === 0) {
    return (
      <div className="max-w-3xl mx-auto p-12 text-center">
        <DollarSign className="w-12 h-12 text-slate-200 mx-auto mb-4" />
        <h1 className="text-xl font-bold text-slate-900 mb-2">AI ROI Dashboard</h1>
        <p className="text-sm text-slate-500">
          Revenue data will appear here once AI-attributed conversions start coming in
          and deal values are tagged via the outcome tracker.
        </p>
      </div>
    );
  }

  // Defensive defaults — partial API responses (missing sub-objects
  // or arrays) would otherwise crash the render with
  // "Cannot read properties of undefined (reading 'toLocaleString')".
  const h = data.headline ?? ({} as Partial<RoiData["headline"]>);
  const headline = {
    totalRevenue: h.totalRevenue ?? 0,
    totalConversions: h.totalConversions ?? 0,
    roiMultiplier: h.roiMultiplier ?? 0,
    revenueGrowth: h.revenueGrowth ?? 0,
    conversionGrowth: h.conversionGrowth ?? 0,
  };
  const f = data.funnel ?? ({} as Partial<RoiData["funnel"]>);
  const funnel = {
    citationsDetected: f.citationsDetected ?? 0,
    referralClicks: f.referralClicks ?? 0,
    engagedVisitors: f.engagedVisitors ?? 0,
    engagementRate: f.engagementRate ?? 0,
    conversions: f.conversions ?? 0,
    qualifiedLeads: f.qualifiedLeads ?? 0,
    qualificationRate: f.qualificationRate ?? 0,
    closedRevenue: f.closedRevenue ?? 0,
  };
  const ca = data.costAnalysis ?? ({} as Partial<RoiData["costAnalysis"]>);
  const costAnalysis = {
    subscriptionCost: ca.subscriptionCost ?? 0,
    aiCreditsUsed: ca.aiCreditsUsed ?? 0,
    totalInvestment: ca.totalInvestment ?? 0,
    totalRevenue: ca.totalRevenue ?? 0,
    roi: ca.roi ?? 0,
    paybackDays: ca.paybackDays ?? null,
  };
  const channelRevenue = Array.isArray(data.channelRevenue) ? data.channelRevenue : [];
  const monthlyTrend = Array.isArray(data.monthlyTrend) ? data.monthlyTrend : [];
  const topPages = Array.isArray(data.topPages) ? data.topPages : [];

  const maxChannelRev = Math.max(...channelRevenue.map((c) => c.revenue ?? 0), 1);

  return (
    <div className="max-w-7xl mx-auto px-4 py-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold text-slate-900">AI ROI Dashboard</h1>
          <p className="text-sm text-slate-500 mt-0.5">Executive summary of AI-attributed revenue</p>
        </div>
        <div className="flex items-center gap-2">
          {["30d", "90d", "180d", "365d"].map((r) => (
            <button
              key={r}
              onClick={() => setRange(r)}
              className={`px-3 py-1.5 text-xs font-semibold rounded-lg transition ${
                range === r ? "bg-brand-600 text-white" : "bg-slate-100 text-slate-600 hover:bg-slate-200"
              }`}
            >
              {r.replace("d", " days")}
            </button>
          ))}
        </div>
      </div>

      {/* Headline Metrics */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <KpiCard
          label="AI-Attributed Revenue"
          value={`$${nfmt(headline.totalRevenue)}`}
          change={headline.revenueGrowth}
          icon={DollarSign}
          color="text-emerald-600"
        />
        <KpiCard
          label="AI Conversions"
          value={headline.totalConversions}
          change={headline.conversionGrowth}
          icon={TrendingUp}
          color="text-blue-600"
        />
        <KpiCard
          label="ROI Multiplier"
          value={`${headline.roiMultiplier}x`}
          icon={Target}
          color="text-violet-600"
        />
        <KpiCard
          label="Revenue Growth"
          value={`${headline.revenueGrowth > 0 ? "+" : ""}${headline.revenueGrowth}%`}
          icon={Zap}
          color={headline.revenueGrowth >= 0 ? "text-emerald-600" : "text-red-600"}
        />
      </div>

      {/* Channel Revenue */}
      <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">
          <BarChart3 className="w-4 h-4 text-brand-600" />
          <h3 className="font-bold text-slate-800 text-sm">Revenue by Channel</h3>
        </div>
        <div className="p-5 space-y-3">
          {channelRevenue.map((c) => (
            <div key={c.channel} className="flex items-center gap-3">
              <span className="text-xs font-bold uppercase tracking-widest text-slate-400 w-16">{CHANNEL_LABELS[c.channel] ?? c.channel}</span>
              <div className="flex-1 bg-slate-100 rounded-full h-6 overflow-hidden">
                <div
                  className={`h-full ${CHANNEL_COLORS[c.channel] ?? "bg-slate-400"} rounded-full flex items-center px-2`}
                  style={{ width: `${Math.max(((c.revenue ?? 0) / maxChannelRev) * 100, 5)}%` }}
                >
                  <span className="text-[10px] font-bold text-white whitespace-nowrap">${nfmt(c.revenue)}</span>
                </div>
              </div>
              <span className="text-xs tabular-nums text-slate-500 w-16 text-right">{c.conversions ?? 0} conv</span>
            </div>
          ))}
        </div>
      </div>

      {/* Revenue Funnel */}
      <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">
          <ArrowDown className="w-4 h-4 text-brand-600" />
          <h3 className="font-bold text-slate-800 text-sm">Revenue Funnel</h3>
        </div>
        <div className="p-5">
          <div className="space-y-0">
            {[
              { label: "AI Citations Detected", value: funnel.citationsDetected, sub: "keywords" },
              { label: "AI Referral Clicks", value: funnel.referralClicks, sub: "visitors" },
              { label: "Engaged Visitors", value: funnel.engagedVisitors, sub: `${funnel.engagementRate}% engagement rate` },
              { label: "Conversions", value: funnel.conversions, sub: "leads" },
              { label: "Qualified Leads", value: funnel.qualifiedLeads, sub: `${funnel.qualificationRate}% qualification rate` },
              { label: "Closed Revenue", value: `$${nfmt(funnel.closedRevenue)}`, sub: "" },
            ].map((step, i, arr) => (
              <div key={step.label}>
                <div className="flex items-center justify-between py-2.5 px-4 bg-slate-50 rounded-lg">
                  <span className="text-sm font-semibold text-slate-700">{step.label}</span>
                  <div className="text-right">
                    <span className="text-lg font-bold text-slate-900 tabular-nums">
                      {typeof step.value === "number" ? nfmt(step.value) : step.value}
                    </span>
                    {step.sub && <span className="text-[10px] text-slate-400 ml-1.5">{step.sub}</span>}
                  </div>
                </div>
                {i < arr.length - 1 && (
                  <div className="flex justify-center py-0.5">
                    <ArrowDown className="w-3 h-3 text-slate-300" />
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Monthly Trend */}
      {monthlyTrend.length > 1 && (
        <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">
            <TrendingUp className="w-4 h-4 text-brand-600" />
            <h3 className="font-bold text-slate-800 text-sm">Monthly AI Revenue Trend</h3>
          </div>
          <div className="p-5">
            <div className="flex items-end gap-2 h-48">
              {monthlyTrend.map((m) => {
                const maxRev = Math.max(...monthlyTrend.map((mm) => mm.totalRevenue ?? 0), 1);
                const rev = m.totalRevenue ?? 0;
                const height = Math.max((rev / maxRev) * 100, 3);
                return (
                  <div key={m.month} className="flex-1 flex flex-col items-center justify-end gap-1">
                    <span className="text-[9px] tabular-nums text-slate-400 font-semibold">
                      ${rev >= 1000 ? `${Math.round(rev / 1000)}k` : rev}
                    </span>
                    <div
                      className="w-full bg-gradient-to-t from-violet-600 to-violet-400 rounded-t"
                      style={{ height: `${height}%` }}
                    />
                    <span className="text-[9px] text-slate-400">{(m.month ?? "").slice(5)}</span>
                  </div>
                );
              })}
            </div>
            <div className="flex items-center gap-4 mt-4 text-[10px]">
              <div className="flex items-center gap-1"><div className="w-2 h-2 rounded-full bg-violet-500" /><span className="text-slate-500">Total Revenue</span></div>
            </div>
          </div>
        </div>
      )}

      {/* Top Performers */}
      {topPages.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">
            <h3 className="font-bold text-slate-800 text-sm">Top Pages by AI Revenue</h3>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-xs">
              <thead className="bg-slate-50 text-[10px] font-bold uppercase tracking-widest text-slate-400">
                <tr>
                  <th className="text-left px-4 py-2">Page</th>
                  <th className="text-right px-3 py-2">Conversions</th>
                  <th className="text-right px-3 py-2">Revenue</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {topPages.map((p) => (
                  <tr key={p.page} className="hover:bg-slate-50">
                    <td className="px-4 py-2.5 font-mono text-brand-600 truncate max-w-[300px]">{p.page}</td>
                    <td className="px-3 py-2.5 text-right tabular-nums">{p.conversions ?? 0}</td>
                    <td className="px-3 py-2.5 text-right tabular-nums font-bold text-emerald-600">${nfmt(p.revenue)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Cost Analysis */}
      <div className="bg-gradient-to-br from-emerald-50 to-blue-50 rounded-xl border border-emerald-200 p-5">
        <div className="flex items-center gap-2 mb-4">
          <DollarSign className="w-4 h-4 text-emerald-600" />
          <h3 className="font-bold text-slate-800 text-sm">Cost Analysis</h3>
        </div>
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
          <div className="bg-white/70 rounded-lg px-3 py-2">
            <p className="text-[9px] font-bold uppercase tracking-widest text-slate-400">Subscription</p>
            <p className="text-lg font-bold text-slate-700 tabular-nums">${nfmt(costAnalysis.subscriptionCost)}/mo</p>
          </div>
          <div className="bg-white/70 rounded-lg px-3 py-2">
            <p className="text-[9px] font-bold uppercase tracking-widest text-slate-400">AI Revenue</p>
            <p className="text-lg font-bold text-emerald-700 tabular-nums">${nfmt(costAnalysis.totalRevenue)}</p>
          </div>
          <div className="bg-white/70 rounded-lg px-3 py-2">
            <p className="text-[9px] font-bold uppercase tracking-widest text-slate-400">ROI</p>
            <p className="text-lg font-bold text-violet-700 tabular-nums">{costAnalysis.roi ?? 0}x return</p>
          </div>
          <div className="bg-white/70 rounded-lg px-3 py-2">
            <p className="text-[9px] font-bold uppercase tracking-widest text-slate-400">Payback</p>
            <p className="text-lg font-bold text-blue-700 tabular-nums">
              {costAnalysis.paybackDays != null ? `${costAnalysis.paybackDays} days` : "—"}
            </p>
            {costAnalysis.paybackDays != null && (
              <p className="text-[10px] text-slate-500">meSEO pays for itself</p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function KpiCard({
  label, value, change, icon: Icon, color,
}: {
  label: string; value: string | number; change?: number; icon: typeof DollarSign; color: string;
}) {
  return (
    <div className="bg-white rounded-xl border border-slate-200 px-5 py-4">
      <div className="flex items-center gap-1.5 mb-1">
        <Icon className={`w-3.5 h-3.5 ${color}`} />
        <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">{label}</p>
      </div>
      <p className={`text-2xl font-bold tabular-nums ${color}`}>
        {typeof value === "number" ? value.toLocaleString() : value}
      </p>
      {change != null && change !== 0 && (
        <p className={`text-[10px] font-semibold mt-0.5 ${change >= 0 ? "text-emerald-600" : "text-red-500"}`}>
          {change > 0 ? "+" : ""}{change}% vs prev period
        </p>
      )}
    </div>
  );
}
