"use client";

import { useEffect, useState } from "react";
import { Loader2, Plus, Minus, X } from "lucide-react";

interface Snapshot { id: string; totalPages: number | null; newPages: unknown; removedPages: unknown; crawledAt: string }

interface Props { competitorId: string; competitorDomain: string; onClose: () => void }

export default function ChangeTimeline({ competitorId, competitorDomain, onClose }: Props) {
  const [snapshots, setSnapshots] = useState<Snapshot[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`/api/competitors/${competitorId}/snapshots`)
      .then((r) => r.ok ? r.json() : null)
      .then((d) => setSnapshots(d?.snapshots ?? []))
      .finally(() => setLoading(false));
  }, [competitorId]);

  if (loading) return <div className="bg-white rounded-xl border border-slate-200 px-5 py-8 text-center"><Loader2 className="w-5 h-5 text-slate-400 animate-spin mx-auto" /></div>;

  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 justify-between">
        <h3 className="font-bold text-slate-800 text-sm">Change History: {competitorDomain}</h3>
        <button onClick={onClose} className="p-1 rounded-md hover:bg-slate-100 text-slate-400"><X className="w-4 h-4" /></button>
      </div>
      {snapshots.length === 0 ? (
        <div className="px-5 py-8 text-center text-xs text-slate-400">No crawl history yet.</div>
      ) : (
        <div className="divide-y divide-slate-100">
          {snapshots.map((snap) => {
            const newP = Array.isArray(snap.newPages) ? (snap.newPages as string[]) : [];
            const remP = Array.isArray(snap.removedPages) ? (snap.removedPages as string[]) : [];
            const date = new Date(snap.crawledAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
            return (
              <div key={snap.id} className="px-5 py-3">
                <div className="flex items-center gap-3 mb-2">
                  <div className="w-2 h-2 rounded-full bg-brand-500 shrink-0" />
                  <span className="text-xs font-semibold text-slate-700">{date}</span>
                  <span className="text-[10px] text-slate-400">{snap.totalPages ?? 0} total pages</span>
                  {newP.length > 0 && <span className="text-[10px] font-bold text-green-600">+{newP.length} new</span>}
                  {remP.length > 0 && <span className="text-[10px] font-bold text-red-500">-{remP.length} removed</span>}
                </div>
                {newP.length > 0 && (
                  <div className="ml-5 space-y-0.5">
                    {newP.slice(0, 5).map((url) => (
                      <div key={url} className="flex items-center gap-1.5 text-[11px]">
                        <Plus className="w-3 h-3 text-green-500 shrink-0" />
                        <a href={url} target="_blank" rel="noopener noreferrer" className="text-brand-600 hover:underline truncate">{url.replace(/^https?:\/\/(www\.)?/, "")}</a>
                      </div>
                    ))}
                    {newP.length > 5 && <p className="ml-4 text-[10px] text-slate-400">+{newP.length - 5} more</p>}
                  </div>
                )}
                {remP.length > 0 && (
                  <div className="ml-5 space-y-0.5 mt-1">
                    {remP.slice(0, 3).map((url) => (
                      <div key={url} className="flex items-center gap-1.5 text-[11px]">
                        <Minus className="w-3 h-3 text-red-500 shrink-0" />
                        <span className="text-slate-500 truncate">{url.replace(/^https?:\/\/(www\.)?/, "")}</span>
                      </div>
                    ))}
                    {remP.length > 3 && <p className="ml-4 text-[10px] text-slate-400">+{remP.length - 3} more</p>}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
