"use client";

import { useState, useEffect, useCallback } from "react";
import { useSearchParams } from "next/navigation";
import {
  Bot, TrendingUp, Users, Eye, Target,
  ArrowDown, Loader2, ExternalLink, Lightbulb,
} from "lucide-react";
import { AiRecommendationsSection, AiRecommendationsBadge } from "./ai-recommendations-section";
import { AiForecastSection } from "./ai-forecast-section";
import { AiCompetitiveTimelineSection } from "./ai-competitive-timeline-section";
import { AiAttributionEmptyState } from "./ai-attribution-empty-state";
import { AiDetectionLogSection } from "./ai-detection-log-section";

interface PlatformRow { platform: string; visits: number; conversions: number }
interface ChannelRow { channel: string; count: number }
interface PageRow { page: string; visits: number }
interface JourneyRow {
  id: string; aiPlatform: string; channel: string; queryContext: string | null;
  referrerUrl: string | null;
  landingPage: string; converted: boolean; conversionType: string | null;
  engagementScore: number | null; timestamp: string;
}
interface ResonanceRow { pageUrl: string; aiVisits: number; aiConvRate: number; organicVisits: number; organicConvRate: number; aiLift: number; resonanceScore: number; recommendation: string }
interface MonitoringStatus {
  installedAt: string | null;
  lastEventAt: string | null;
  sessionsScanned: number;
  isActive: boolean;
}
interface AiData {
  totalReferrals: number; conversions: number; conversionRate: number;
  byPlatform: PlatformRow[]; byChannel: ChannelRow[]; topPages: PageRow[];
  dailyTrend: Array<{ date: string; count: number }>;
  recentJourneys: JourneyRow[];
  contentResonance?: ResonanceRow[];
  multiTouch?: { direct: number; assisted: number };
  probableAiCount?: number;
  monitoring?: MonitoringStatus;
}

function inferQueryFromUrl(url: string): string {
  try {
    const pathname = new URL(url, "https://x").pathname;
    const clean = pathname.replace(/^\/([a-z]{2})\//, "/").replace(/\/$/, "");
    const slug = clean.split("/").filter(Boolean).pop() ?? "";
    const words = slug.replace(/[-_]/g, " ").replace(/[^a-z0-9 ]/gi, "").trim();
    if (!words) return url;
    return words.charAt(0).toUpperCase() + words.slice(1);
  } catch {
    return url;
  }
}

const PLATFORM_LABELS: Record<string, string> = {
  chatgpt: "ChatGPT", perplexity: "Perplexity", gemini: "Gemini",
  copilot: "Microsoft Copilot", claude: "Claude", you_com: "You.com",
  phind: "Phind", meta_ai: "Meta AI", poe: "Poe",
  google_ai_overview: "Google AI Overview",
};
const CHANNEL_LABELS: Record<string, string> = { llmo: "LLMO", geo: "GEO", aeo: "AEO" };

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

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

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

  // Scroll to the Recommendations section when the sidebar link is
  // used (/site-tag-analytics?tab=ai&view=recommendations). Runs after
  // data loads so the section has actually mounted.
  const searchParams = useSearchParams();
  useEffect(() => {
    if (searchParams.get("view") === "recommendations" && !loading) {
      const el = document.getElementById("ai-recommendations");
      if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
    }
  }, [searchParams, loading]);

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

  // Treat any falsy totalReferrals (undefined from malformed responses,
  // zero from a freshly-installed tag) as the empty state so the rest
  // of the render can trust that numeric/array fields are populated.
  if (!data || !data.totalReferrals) {
    return (
      <div className="space-y-6">
        <AiAttributionEmptyState monitoring={data?.monitoring ?? null} />
        <AiDetectionLogSection brandId={brandId} />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Recommendations badge */}
      <AiRecommendationsBadge brandId={brandId} />

      {/* KPI cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <KpiCard label="AI Referrals" value={data.totalReferrals} icon={Bot} color="text-violet-600" />
        <KpiCard label="Conversions" value={data.conversions} icon={TrendingUp} color="text-emerald-600" />
        <KpiCard label="Conversion Rate" value={`${data.conversionRate}%`} icon={Target} color="text-blue-600" />
        <KpiCard
          label="Top Platform"
          value={PLATFORM_LABELS[data.byPlatform[0]?.platform] ?? data.byPlatform[0]?.platform ?? "—"}
          icon={Eye}
          color="text-amber-600"
        />
      </div>

      {/* Channel comparison */}
      {data.byChannel.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">
            <Target className="w-4 h-4 text-brand-600" />
            <h3 className="font-bold text-slate-800 text-sm">By Channel</h3>
          </div>
          <div className="grid grid-cols-3 divide-x divide-slate-100">
            {["llmo", "geo", "aeo"].map((ch) => {
              const row = data.byChannel.find((c) => c.channel === ch);
              return (
                <div key={ch} className="px-5 py-4 text-center">
                  <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-1">{CHANNEL_LABELS[ch]}</p>
                  <p className="text-2xl font-bold text-slate-900 tabular-nums">{row?.count ?? 0}</p>
                  <p className="text-[11px] text-slate-500">referrals</p>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* By platform */}
      {data.byPlatform.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">
            <Users className="w-4 h-4 text-brand-600" />
            <h3 className="font-bold text-slate-800 text-sm">By Platform</h3>
          </div>
          <div className="divide-y divide-slate-100">
            {data.byPlatform.map((p) => {
              const rate = p.visits > 0 ? Math.round((p.conversions / p.visits) * 1000) / 10 : 0;
              return (
                <div key={p.platform} className="px-5 py-3 flex items-center gap-4">
                  <span className="text-sm font-semibold text-slate-800 flex-1">{PLATFORM_LABELS[p.platform] ?? p.platform}</span>
                  <span className="text-sm tabular-nums text-slate-600">{p.visits} visits</span>
                  <span className="text-sm tabular-nums text-emerald-600 font-semibold">{p.conversions} conv.</span>
                  <span className="text-xs tabular-nums text-slate-400 w-12 text-right">{rate}%</span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Top AI-attributed pages */}
      {data.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 flex items-center gap-2">
            <ExternalLink className="w-4 h-4 text-brand-600" />
            <h3 className="font-bold text-slate-800 text-sm">Top AI Landing Pages</h3>
          </div>
          <div className="divide-y divide-slate-100">
            {data.topPages.map((p) => (
              <div key={p.page} className="px-5 py-3 flex items-center gap-4">
                <span className="text-sm font-mono text-brand-600 truncate flex-1" title={p.page}>{p.page}</span>
                <span className="text-sm tabular-nums text-slate-600 shrink-0">{p.visits} visits</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Recent journeys */}
      {data.recentJourneys.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">
            <ArrowDown className="w-4 h-4 text-brand-600" />
            <h3 className="font-bold text-slate-800 text-sm">Recent AI Journeys</h3>
          </div>
          <div className="divide-y divide-slate-100">
            {data.recentJourneys.slice(0, 10).map((j) => (
              <div key={j.id} className="px-5 py-3 space-y-1">
                <div className="flex items-center gap-3">
                  <span className={`text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded ${
                    j.channel === "llmo" ? "bg-violet-50 text-violet-700" :
                    j.channel === "geo" ? "bg-blue-50 text-blue-700" :
                    "bg-amber-50 text-amber-700"
                  }`}>{j.channel}</span>
                  <span className="text-xs font-semibold text-slate-700">{PLATFORM_LABELS[j.aiPlatform] ?? j.aiPlatform}</span>
                  {(() => {
                    const q = j.queryContext;
                    const isInferred = !q || q.startsWith("[inferred]");
                    const displayQuery = isInferred
                      ? (q ? q.replace(/^\[inferred\]\s*/i, "") : inferQueryFromUrl(j.landingPage))
                      : q;
                    if (!displayQuery) return <span className="text-xs text-slate-300 truncate flex-1">—</span>;
                    return (
                      <span className="text-xs text-slate-700 truncate flex-1" title={displayQuery}>
                        &ldquo;{displayQuery}&rdquo;
                        {isInferred && (
                          <span className="text-[10px] text-slate-400 not-italic ml-1">(inferred)</span>
                        )}
                      </span>
                    );
                  })()}
                  <span className="text-xs font-mono text-slate-500 truncate max-w-[150px]">{j.landingPage}</span>
                  {j.converted && (
                    <span className="text-[10px] font-bold text-emerald-600 bg-emerald-50 px-1.5 py-0.5 rounded">{j.conversionType ?? "Converted"}</span>
                  )}
                </div>
                {j.referrerUrl && (
                  <p className="text-[10px] font-mono text-slate-400 truncate pl-[60px]" title={j.referrerUrl}>
                    Referrer: {j.referrerUrl}
                  </p>
                )}
              </div>
            ))}
          </div>
        </div>
      )}
      {/* Multi-Touch Attribution */}
      {data.multiTouch && (data.multiTouch.direct > 0 || data.multiTouch.assisted > 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">
            <TrendingUp className="w-4 h-4 text-brand-600" />
            <h3 className="font-bold text-slate-800 text-sm">Multi-Touch AI Attribution</h3>
          </div>
          <div className="grid grid-cols-3 divide-x divide-slate-100 px-5 py-4">
            <div className="text-center">
              <p className="text-[9px] font-bold uppercase tracking-widest text-slate-400">Direct</p>
              <p className="text-2xl font-bold text-emerald-600 tabular-nums">{data.multiTouch.direct}</p>
              <p className="text-[10px] text-slate-500">AI → conversion same session</p>
            </div>
            <div className="text-center">
              <p className="text-[9px] font-bold uppercase tracking-widest text-slate-400">Assisted</p>
              <p className="text-2xl font-bold text-blue-600 tabular-nums">{data.multiTouch.assisted}</p>
              <p className="text-[10px] text-slate-500">AI touch → later conversion</p>
            </div>
            <div className="text-center">
              <p className="text-[9px] font-bold uppercase tracking-widest text-slate-400">Behavioral</p>
              <p className="text-2xl font-bold text-amber-600 tabular-nums">{data.probableAiCount ?? 0}</p>
              <p className="text-[10px] text-slate-500">Probable AI (model detected)</p>
            </div>
          </div>
        </div>
      )}

      {/* Content Resonance */}
      {data.contentResonance && data.contentResonance.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">
            <Target className="w-4 h-4 text-brand-600" />
            <h3 className="font-bold text-slate-800 text-sm">Content Resonance — AI vs Organic</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">AI Visits</th>
                  <th className="text-right px-3 py-2">AI Conv%</th>
                  <th className="text-right px-3 py-2">Organic</th>
                  <th className="text-right px-3 py-2">Org Conv%</th>
                  <th className="text-right px-3 py-2">AI Lift</th>
                  <th className="text-right px-3 py-2">Score</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {data.contentResonance.map((r) => (
                  <tr key={r.pageUrl} className="hover:bg-slate-50" title={r.recommendation}>
                    <td className="px-4 py-2 font-mono text-brand-600 truncate max-w-[200px]">{r.pageUrl}</td>
                    <td className="px-3 py-2 text-right tabular-nums">{r.aiVisits}</td>
                    <td className="px-3 py-2 text-right tabular-nums text-emerald-600 font-semibold">{r.aiConvRate}%</td>
                    <td className="px-3 py-2 text-right tabular-nums">{r.organicVisits}</td>
                    <td className="px-3 py-2 text-right tabular-nums">{r.organicConvRate}%</td>
                    <td className="px-3 py-2 text-right tabular-nums font-bold">{r.aiLift > 0 ? `${r.aiLift}x` : "—"}</td>
                    <td className="px-3 py-2 text-right tabular-nums font-bold text-violet-600">{r.resonanceScore}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* AI Traffic Quality scorecard */}
      {data.totalReferrals > 5 && (
        <div className="bg-gradient-to-br from-violet-50 to-blue-50 rounded-xl border border-violet-200 p-5">
          <div className="flex items-center gap-2 mb-3">
            <Bot className="w-4 h-4 text-violet-600" />
            <h3 className="font-bold text-slate-800 text-sm">AI Traffic Quality</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">AI Conv. Rate</p>
              <p className="text-lg font-bold text-violet-700 tabular-nums">{data.conversionRate}%</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">Platforms Detected</p>
              <p className="text-lg font-bold text-blue-700 tabular-nums">{data.byPlatform.length}</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">Queries Captured</p>
              <p className="text-lg font-bold text-emerald-700 tabular-nums">
                {data.recentJourneys.filter((j) => j.queryContext && !j.queryContext.startsWith("[inferred]")).length}
              </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">Queries Inferred</p>
              <p className="text-lg font-bold text-amber-700 tabular-nums">
                {data.recentJourneys.filter((j) => j.queryContext?.startsWith("[inferred]")).length}
              </p>
            </div>
          </div>
          <p className="text-[11px] text-slate-500 mt-3">
            Captured queries are extracted from referrer URLs. Inferred queries are reconstructed from the landing page URL when the AI platform strips query context.
          </p>
        </div>
      )}

      {/* AI Recommendations */}
      <section id="ai-recommendations" className="scroll-mt-20">
        <AiRecommendationsSection brandId={brandId} />
      </section>

      {/* Competitive AI Timeline */}
      <AiCompetitiveTimelineSection brandId={brandId} />

      {/* AI Forecast */}
      <AiForecastSection brandId={brandId} />

      {/* Detection Log */}
      <AiDetectionLogSection brandId={brandId} />
    </div>
  );
}

function KpiCard({ label, value, icon: Icon, color }: { label: string; value: string | number; icon: typeof Bot; 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>
    </div>
  );
}
