"use client";

import { useState, useEffect, useCallback } from "react";
import {
  ScrollText, ChevronDown, ChevronUp, CheckCircle2, Circle,
  RefreshCw, Loader2,
} from "lucide-react";

interface LogEntry {
  sessionId: string;
  timestamp: string;
  referrer: string | null;
  landingPage: string;
  classification: "ai_overview" | "ai_platform" | "organic" | "direct" | "other";
  platform: string | null;
  hasTextFragment: boolean;
  reason: string;
  attributed: boolean;
}

const CLASS_STYLE: Record<LogEntry["classification"], { label: string; color: string }> = {
  ai_overview:  { label: "AI Overview",  color: "bg-blue-50 text-blue-700 border-blue-200" },
  ai_platform:  { label: "AI platform",  color: "bg-violet-50 text-violet-700 border-violet-200" },
  organic:      { label: "Organic",      color: "bg-slate-50 text-slate-600 border-slate-200" },
  direct:       { label: "Direct",       color: "bg-slate-50 text-slate-500 border-slate-200" },
  other:        { label: "Other",        color: "bg-slate-50 text-slate-500 border-slate-200" },
};

function timeAgo(iso: string): string {
  const diff = Date.now() - new Date(iso).getTime();
  const m = Math.floor(diff / 60_000);
  if (m < 1) return "just now";
  if (m < 60) return `${m} min ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h} hr ago`;
  const d = Math.floor(h / 24);
  return `${d}d ago`;
}

function trimPath(url: string | null, maxLen = 40): string {
  if (!url) return "—";
  try {
    const u = new URL(url);
    const path = u.pathname + u.search;
    return path.length > maxLen ? path.slice(0, maxLen) + "…" : path;
  } catch {
    return url.length > maxLen ? url.slice(0, maxLen) + "…" : url;
  }
}

function trimReferrer(ref: string | null): string {
  if (!ref) return "(none)";
  try {
    return new URL(ref).hostname;
  } catch {
    return ref.slice(0, 50);
  }
}

export function AiDetectionLogSection({ brandId }: { brandId: string }) {
  const [entries, setEntries] = useState<LogEntry[]>([]);
  const [loading, setLoading] = useState(false);
  const [expanded, setExpanded] = useState(false);
  const [loadedOnce, setLoadedOnce] = useState(false);

  const load = useCallback(async () => {
    if (!brandId) return;
    setLoading(true);
    try {
      const res = await fetch(`/api/site-tag/analytics/ai-detection-log?brandId=${brandId}&limit=20`);
      if (res.ok) {
        const data = await res.json();
        setEntries(data.entries ?? []);
      }
    } catch { /* silent */ }
    setLoading(false);
    setLoadedOnce(true);
  }, [brandId]);

  useEffect(() => {
    if (expanded && !loadedOnce) load();
  }, [expanded, loadedOnce, load]);

  const aiCount = entries.filter((e) => e.classification === "ai_overview" || e.classification === "ai_platform").length;

  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      <button
        onClick={() => setExpanded((x) => !x)}
        className="w-full px-5 py-3.5 border-b border-slate-100 flex items-center gap-2 text-left hover:bg-slate-50 transition-colors"
      >
        <ScrollText className="w-4 h-4 text-brand-600" />
        <h3 className="font-bold text-slate-800 text-sm">Detection Log</h3>
        <span className="text-xs text-slate-400">— see how recent sessions were classified</span>
        <span className="ml-auto flex items-center gap-2">
          {loadedOnce && entries.length > 0 && (
            <span className="text-[10px] font-semibold text-slate-500">
              {aiCount}/{entries.length} AI detected
            </span>
          )}
          {expanded ? <ChevronUp className="w-4 h-4 text-slate-400" /> : <ChevronDown className="w-4 h-4 text-slate-400" />}
        </span>
      </button>

      {expanded && (
        <div>
          <div className="px-5 py-2.5 border-b border-slate-100 flex items-center justify-between bg-slate-50">
            <p className="text-[10px] text-slate-500">
              Last {entries.length || 20} sessions analyzed. Refresh to see new activity.
            </p>
            <button
              onClick={load}
              disabled={loading}
              className="flex items-center gap-1 text-[10px] font-semibold text-brand-600 hover:text-brand-700 disabled:opacity-40"
            >
              {loading ? <Loader2 className="w-3 h-3 animate-spin" /> : <RefreshCw className="w-3 h-3" />}
              Refresh
            </button>
          </div>

          {loading && entries.length === 0 ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="w-4 h-4 text-brand-500 animate-spin" />
            </div>
          ) : entries.length === 0 ? (
            <div className="px-5 py-8 text-center">
              <p className="text-xs text-slate-400">No recent sessions to analyze.</p>
            </div>
          ) : (
            <div className="divide-y divide-slate-100 max-h-96 overflow-y-auto">
              {entries.map((entry) => {
                const style = CLASS_STYLE[entry.classification];
                return (
                  <div key={`${entry.sessionId}-${entry.timestamp}`} className="px-5 py-2.5 text-xs">
                    <div className="flex items-center gap-2 flex-wrap">
                      <span className="text-slate-400 tabular-nums shrink-0 w-16">
                        {timeAgo(entry.timestamp)}
                      </span>
                      <span className={`text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded border ${style.color} shrink-0`}>
                        {style.label}
                      </span>
                      {entry.attributed && (
                        <span className="inline-flex items-center gap-0.5 text-[9px] font-bold text-emerald-600">
                          <CheckCircle2 className="w-2.5 h-2.5" />
                          Attributed
                        </span>
                      )}
                      {!entry.attributed && entry.classification !== "ai_overview" && entry.classification !== "ai_platform" && (
                        <span className="inline-flex items-center gap-0.5 text-[9px] font-semibold text-slate-400">
                          <Circle className="w-2.5 h-2.5" />
                          Not AI
                        </span>
                      )}
                      <span className="text-slate-500 truncate" title={entry.referrer ?? ""}>
                        {trimReferrer(entry.referrer)}
                      </span>
                      <span className="text-slate-300">→</span>
                      <span className="text-brand-600 font-mono truncate" title={entry.landingPage}>
                        {trimPath(entry.landingPage)}
                      </span>
                      {entry.hasTextFragment && (
                        <span className="text-[9px] font-bold text-blue-600 bg-blue-50 border border-blue-200 rounded px-1 py-0.5">
                          text fragment
                        </span>
                      )}
                    </div>
                    <p className="text-[10px] text-slate-400 mt-0.5 ml-[72px]">{entry.reason}</p>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
