"use client";

import { useState, useEffect, useCallback } from "react";
import { Shield, Loader2, TrendingUp, TrendingDown, Minus } from "lucide-react";

interface TimelineEntry {
  keyword: string;
  checkedAt: string;
  brandCited: boolean;
  citedPosition: number | null;
  competitors: Array<{ domain: string; position: number }>;
}

export function AiCompetitiveTimelineSection({ brandId }: { brandId: string }) {
  const [timeline, setTimeline] = useState<TimelineEntry[]>([]);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    if (!brandId) return;
    setLoading(true);
    try {
      const res = await fetch(`/api/ai-competitive-timeline?brandId=${brandId}&limit=30`);
      if (res.ok) {
        const data = await res.json();
        setTimeline(data.timeline ?? []);
      }
    } 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 (timeline.length === 0) {
    return (
      <div className="bg-white rounded-xl border border-slate-200 p-8 text-center">
        <Shield className="w-8 h-8 text-slate-200 mx-auto mb-2" />
        <h3 className="text-sm font-bold text-slate-900 mb-1">Competitive AI Timeline</h3>
        <p className="text-xs text-slate-500 max-w-sm mx-auto">
          Position tracking data will appear after the weekly AI citation check runs.
        </p>
      </div>
    );
  }

  const byKeyword = new Map<string, TimelineEntry[]>();
  for (const entry of timeline) {
    const list = byKeyword.get(entry.keyword) ?? [];
    list.push(entry);
    byKeyword.set(entry.keyword, list);
  }

  return (
    <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">
        <Shield className="w-4 h-4 text-brand-600" />
        <h3 className="font-bold text-slate-800 text-sm">Competitive AI Timeline</h3>
      </div>
      <div className="divide-y divide-slate-100">
        {[...byKeyword.entries()].slice(0, 10).map(([keyword, entries]) => (
          <div key={keyword} className="px-5 py-3">
            <p className="text-sm font-semibold text-slate-800 mb-2">&ldquo;{keyword}&rdquo;</p>
            <div className="space-y-1">
              {entries.slice(0, 4).map((entry, i) => {
                const date = new Date(entry.checkedAt).toLocaleDateString("en-US", { month: "short", day: "numeric" });
                const prevEntry = entries[i + 1];
                const posChanged = prevEntry && prevEntry.brandCited !== entry.brandCited;

                return (
                  <div key={`${entry.keyword}-${entry.checkedAt}`} className="flex items-center gap-3 text-xs">
                    <span className="text-slate-400 tabular-nums w-14 shrink-0">{date}</span>
                    {entry.brandCited ? (
                      <span className="flex items-center gap-1">
                        {posChanged ? (
                          <TrendingUp className="w-3 h-3 text-emerald-500" />
                        ) : (
                          <Minus className="w-3 h-3 text-slate-300" />
                        )}
                        <span className="font-semibold text-emerald-600">
                          You: #{entry.citedPosition ?? "?"}
                        </span>
                      </span>
                    ) : (
                      <span className="flex items-center gap-1">
                        {posChanged ? (
                          <TrendingDown className="w-3 h-3 text-red-500" />
                        ) : (
                          <Minus className="w-3 h-3 text-slate-300" />
                        )}
                        <span className="text-slate-400">Not cited</span>
                      </span>
                    )}
                    {entry.competitors.length > 0 && (
                      <span className="text-slate-400">
                        {entry.competitors.slice(0, 2).map((c) => `${c.domain} #${c.position}`).join(", ")}
                      </span>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
