"use client";

import { useState, useEffect, useCallback } from "react";
import { useBrand } from "@/context/brand-context";
import {
  Activity, FileText, RefreshCw, Trash2, PenLine,
  ExternalLink, Loader2, ChevronDown,
} from "lucide-react";

interface ActivityItem {
  competitorId: string;
  competitorDomain: string;
  url: string;
  title: string | null;
  status: string;  // new | updated | removed
  firstSeenAt: string;
  lastCheckedAt: string;
}

const STATUS_CONFIG: Record<string, { label: string; color: string; bg: string; border: string; icon: typeof FileText }> = {
  new:     { label: "New",     color: "text-emerald-700", bg: "bg-emerald-50", border: "border-emerald-200", icon: FileText },
  updated: { label: "Updated", color: "text-blue-700",    bg: "bg-blue-50",    border: "border-blue-200",    icon: PenLine },
  removed: { label: "Removed", color: "text-red-700",     bg: "bg-red-50",     border: "border-red-200",     icon: Trash2 },
};

export default function RecentActivity() {
  const { brand } = useBrand();
  const [items, setItems] = useState<ActivityItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<string>("all");
  const [visibleCount, setVisibleCount] = useState(20);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/competitors/analysis?brandId=${brand.id}&type=activity&days=30`);
      if (res.ok) {
        const data = await res.json();
        setItems(data.activity ?? []);
      }
    } catch { /* swallow */ }
    setLoading(false);
  }, [brand.id]);

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

  const filtered = filter === "all" ? items : items.filter((i) => i.status === filter);
  const visible = filtered.slice(0, visibleCount);

  const counts = { all: items.length, new: 0, updated: 0, removed: 0 };
  for (const i of items) {
    if (i.status in counts) (counts as Record<string, number>)[i.status]++;
  }

  if (loading) {
    return (
      <div className="bg-white rounded-xl border border-slate-200 p-8 flex items-center justify-center">
        <Loader2 className="w-5 h-5 animate-spin text-slate-400" />
      </div>
    );
  }

  if (items.length === 0) {
    return (
      <div className="bg-white rounded-xl border border-dashed border-slate-200 p-10 text-center">
        <Activity className="w-8 h-8 text-slate-200 mx-auto mb-2" />
        <p className="text-sm font-semibold text-slate-600">No recent activity</p>
        <p className="text-xs text-slate-400 mt-1">Competitor sitemap changes will appear here after the next crawl.</p>
      </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">
        <div className="flex items-center gap-2">
          <Activity className="w-4 h-4 text-brand-600" />
          <h3 className="font-bold text-slate-800 text-sm">Recent Activity</h3>
          <span className="text-[10px] font-semibold text-slate-400 ml-1">Last 30 days</span>
        </div>
        <button onClick={load} className="text-[10px] font-semibold text-slate-500 hover:text-slate-700 flex items-center gap-1">
          <RefreshCw className="w-3 h-3" /> Refresh
        </button>
      </div>

      {/* Filter tabs */}
      <div className="px-5 py-2.5 border-b border-slate-100 flex items-center gap-1">
        {(["all", "new", "updated", "removed"] as const).map((key) => (
          <button
            key={key}
            onClick={() => { setFilter(key); setVisibleCount(20); }}
            className={`px-2.5 py-1.5 rounded-lg text-[11px] font-semibold transition-colors ${
              filter === key ? "bg-slate-900 text-white" : "text-slate-500 hover:bg-slate-100"
            }`}
          >
            {key === "all" ? "All" : STATUS_CONFIG[key].label}
            <span className={`ml-1 ${filter === key ? "text-slate-300" : "text-slate-400"}`}>
              {(counts as Record<string, number>)[key]}
            </span>
          </button>
        ))}
      </div>

      {/* Activity list */}
      <div className="divide-y divide-slate-100">
        {visible.map((item, i) => {
          const cfg = STATUS_CONFIG[item.status] ?? STATUS_CONFIG.new;
          const Icon = cfg.icon;
          return (
            <div key={`${item.url}-${i}`} className="px-5 py-3 flex items-center gap-3 hover:bg-slate-50 transition-colors">
              <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-bold ${cfg.bg} ${cfg.color} ${cfg.border} border shrink-0`}>
                <Icon className="w-3 h-3" />
                {cfg.label}
              </span>
              <div className="flex-1 min-w-0">
                <a
                  href={item.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-xs font-medium text-slate-800 hover:text-brand-600 hover:underline truncate block"
                  title={item.url}
                >
                  {item.title || new URL(item.url).pathname}
                  <ExternalLink className="w-2.5 h-2.5 inline ml-1 text-slate-300" />
                </a>
                <p className="text-[10px] text-slate-400 mt-0.5 truncate">
                  {item.competitorDomain} · {new Date(item.lastCheckedAt).toLocaleDateString(undefined, { month: "short", day: "numeric" })}
                </p>
              </div>
            </div>
          );
        })}
      </div>

      {/* Load more */}
      {filtered.length > visibleCount && (
        <button
          onClick={() => setVisibleCount((c) => c + 20)}
          className="w-full py-3 text-[11px] font-semibold text-slate-500 hover:text-slate-700 hover:bg-slate-50 border-t border-slate-100 flex items-center justify-center gap-1"
        >
          <ChevronDown className="w-3 h-3" />
          Show more ({filtered.length - visibleCount} remaining)
        </button>
      )}
    </div>
  );
}
