"use client";

import { useState, useEffect, useCallback } from "react";
import { useBrand } from "@/context/brand-context";
import {
  Search, ExternalLink, Loader2, FileText, AlertCircle,
  ChevronDown, ChevronUp,
} from "lucide-react";

interface ContentGap {
  competitorId: string;
  competitorDomain: string;
  competitorUrl: string;
  competitorTitle: string | null;
  topic: string;
  wordCount: number | null;
  lastmod: string | null;
  firstSeenAt: string;
  matchConfidence: number;
}

interface HeadToHead {
  topic: string;
  brandUrl: string;
  brandTitle: string | null;
  competitorId: string;
  competitorDomain: string;
  competitorUrl: string;
  competitorTitle: string | null;
  competitorWordCount: number | null;
  competitorLastmod: string | null;
  matchConfidence: number;
}

interface AnalysisData {
  gaps: ContentGap[];
  headToHead: HeadToHead[];
  brandPageCount: number;
  competitorPageCount: number;
}

type SortKey = "topic" | "domain" | "wordCount" | "firstSeenAt" | "confidence";

function ConfidenceDot({ value }: { value: number }) {
  const pct = Math.round(value * 100);
  const color = pct >= 80 ? "bg-emerald-500" : pct >= 60 ? "bg-amber-500" : "bg-slate-300";
  return (
    <span className="inline-flex items-center gap-1" title={`${pct}% confidence`}>
      <span className={`w-1.5 h-1.5 rounded-full ${color}`} />
      <span className="text-[10px] text-slate-400 tabular-nums">{pct}%</span>
    </span>
  );
}

export default function ContentGaps() {
  const { brand } = useBrand();
  const [data, setData] = useState<AnalysisData | null>(null);
  const [loading, setLoading] = useState(true);
  const [tab, setTab] = useState<"gaps" | "h2h">("gaps");
  const [search, setSearch] = useState("");
  const [sortBy, setSortBy] = useState<SortKey>("firstSeenAt");
  const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");
  const [visibleCount, setVisibleCount] = useState(25);

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

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

  function toggleSort(key: SortKey) {
    if (sortBy === key) setSortDir((d) => d === "asc" ? "desc" : "asc");
    else { setSortBy(key); setSortDir("desc"); }
    setVisibleCount(25);
  }

  const SortIcon = ({ col }: { col: SortKey }) => {
    if (sortBy !== col) return null;
    return sortDir === "asc" ? <ChevronUp className="w-3 h-3 inline" /> : <ChevronDown className="w-3 h-3 inline" />;
  };

  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 (!data || (data.gaps.length === 0 && data.headToHead.length === 0)) {
    return (
      <div className="bg-white rounded-xl border border-dashed border-slate-200 p-10 text-center">
        <Search className="w-8 h-8 text-slate-200 mx-auto mb-2" />
        <p className="text-sm font-semibold text-slate-600">No content gaps detected yet</p>
        <p className="text-xs text-slate-400 mt-1">Crawl competitor sitemaps first, then the analysis will compare their pages against yours.</p>
      </div>
    );
  }

  // ── Gap tab data ──────────────────────────────────────────────────
  const searchLower = search.toLowerCase();
  const filteredGaps = data.gaps.filter((g) =>
    !search || g.topic.includes(searchLower) || (g.competitorTitle ?? "").toLowerCase().includes(searchLower) || g.competitorDomain.includes(searchLower),
  );
  const sortedGaps = [...filteredGaps].sort((a, b) => {
    const dir = sortDir === "asc" ? 1 : -1;
    if (sortBy === "topic") return dir * a.topic.localeCompare(b.topic);
    if (sortBy === "domain") return dir * a.competitorDomain.localeCompare(b.competitorDomain);
    if (sortBy === "wordCount") return dir * ((a.wordCount ?? 0) - (b.wordCount ?? 0));
    if (sortBy === "confidence") return dir * (a.matchConfidence - b.matchConfidence);
    return dir * a.firstSeenAt.localeCompare(b.firstSeenAt);
  });
  const visibleGaps = sortedGaps.slice(0, visibleCount);

  // ── H2H tab data ─────────────────────────────────────────────────
  const filteredH2H = data.headToHead.filter((h) =>
    !search || h.topic.includes(searchLower) || (h.competitorTitle ?? "").toLowerCase().includes(searchLower),
  );
  const visibleH2H = filteredH2H.slice(0, visibleCount);

  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      {/* Header */}
      <div className="px-5 py-3.5 border-b border-slate-100 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <AlertCircle className="w-4 h-4 text-brand-600" />
          <h3 className="font-bold text-slate-800 text-sm">Content Analysis</h3>
          <span className="text-[10px] font-semibold text-slate-400">
            {data.brandPageCount} brand pages vs {data.competitorPageCount} competitor pages
          </span>
        </div>
      </div>

      {/* Tab bar + search */}
      <div className="px-5 py-2.5 border-b border-slate-100 flex items-center justify-between gap-4">
        <div className="flex items-center gap-1">
          <button onClick={() => { setTab("gaps"); setVisibleCount(25); }} className={`px-3 py-1.5 rounded-lg text-[11px] font-semibold ${tab === "gaps" ? "bg-amber-50 text-amber-700 border border-amber-200" : "text-slate-500 hover:bg-slate-100"}`}>
            Content Gaps <span className="ml-1 text-[10px]">{data.gaps.length}</span>
          </button>
          <button onClick={() => { setTab("h2h"); setVisibleCount(25); }} className={`px-3 py-1.5 rounded-lg text-[11px] font-semibold ${tab === "h2h" ? "bg-blue-50 text-blue-700 border border-blue-200" : "text-slate-500 hover:bg-slate-100"}`}>
            Head-to-Head <span className="ml-1 text-[10px]">{data.headToHead.length}</span>
          </button>
        </div>
        <div className="relative">
          <Search className="w-3 h-3 text-slate-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
          <input
            value={search} onChange={(e) => { setSearch(e.target.value); setVisibleCount(25); }}
            placeholder="Search topics..."
            className="pl-7 pr-3 py-1.5 text-[11px] border border-slate-200 rounded-lg w-48 focus:outline-none focus:ring-2 focus:ring-brand-500/40"
          />
        </div>
      </div>

      {/* Content Gaps table */}
      {tab === "gaps" && (
        <>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 border-b border-slate-100 bg-slate-50">
                  <th className="px-5 py-2.5 cursor-pointer hover:text-slate-600" onClick={() => toggleSort("topic")}>Topic <SortIcon col="topic" /></th>
                  <th className="px-5 py-2.5">Competitor URL</th>
                  <th className="px-5 py-2.5 cursor-pointer hover:text-slate-600" onClick={() => toggleSort("domain")}>Domain <SortIcon col="domain" /></th>
                  <th className="px-5 py-2.5 text-right cursor-pointer hover:text-slate-600" onClick={() => toggleSort("wordCount")}>Words <SortIcon col="wordCount" /></th>
                  <th className="px-5 py-2.5 text-right cursor-pointer hover:text-slate-600" onClick={() => toggleSort("firstSeenAt")}>Detected <SortIcon col="firstSeenAt" /></th>
                  <th className="px-5 py-2.5 text-right cursor-pointer hover:text-slate-600" onClick={() => toggleSort("confidence")}>Conf. <SortIcon col="confidence" /></th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {visibleGaps.map((g, i) => (
                  <tr key={`${g.competitorUrl}-${i}`} className="hover:bg-slate-50 transition-colors">
                    <td className="px-5 py-2.5">
                      <p className="text-xs font-semibold text-slate-800 capitalize">{g.topic}</p>
                      {g.competitorTitle && <p className="text-[10px] text-slate-400 truncate max-w-[280px]">{g.competitorTitle}</p>}
                    </td>
                    <td className="px-5 py-2.5">
                      <a href={g.competitorUrl} target="_blank" rel="noopener noreferrer" className="text-[11px] font-mono text-brand-600 hover:underline truncate max-w-[300px] inline-flex items-center gap-1">
                        {new URL(g.competitorUrl).pathname} <ExternalLink className="w-2.5 h-2.5 text-slate-300 shrink-0" />
                      </a>
                    </td>
                    <td className="px-5 py-2.5 text-[11px] text-slate-600">{g.competitorDomain}</td>
                    <td className="px-5 py-2.5 text-right text-xs text-slate-500 tabular-nums">{g.wordCount?.toLocaleString() ?? "—"}</td>
                    <td className="px-5 py-2.5 text-right text-[11px] text-slate-400 tabular-nums">{new Date(g.firstSeenAt).toLocaleDateString(undefined, { month: "short", day: "numeric" })}</td>
                    <td className="px-5 py-2.5 text-right"><ConfidenceDot value={g.matchConfidence} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {sortedGaps.length > visibleCount && (
            <button onClick={() => setVisibleCount((c) => c + 25)} 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 ({sortedGaps.length - visibleCount} remaining)
            </button>
          )}
        </>
      )}

      {/* Head-to-Head table */}
      {tab === "h2h" && (
        <>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 border-b border-slate-100 bg-slate-50">
                  <th className="px-5 py-2.5">Topic</th>
                  <th className="px-5 py-2.5">Your Page</th>
                  <th className="px-5 py-2.5">Competitor Page</th>
                  <th className="px-5 py-2.5 text-right">Comp. Words</th>
                  <th className="px-5 py-2.5 text-right">Comp. Updated</th>
                  <th className="px-5 py-2.5 text-right">Conf.</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {visibleH2H.map((h, i) => (
                  <tr key={`${h.brandUrl}-${h.competitorUrl}-${i}`} className="hover:bg-slate-50 transition-colors">
                    <td className="px-5 py-2.5 text-xs font-semibold text-slate-800 capitalize">{h.topic}</td>
                    <td className="px-5 py-2.5">
                      <span className="text-[11px] font-mono text-emerald-600 truncate max-w-[200px] inline-block" title={h.brandUrl}>{h.brandUrl}</span>
                      {h.brandTitle && <p className="text-[10px] text-slate-400 truncate max-w-[200px]">{h.brandTitle}</p>}
                    </td>
                    <td className="px-5 py-2.5">
                      <a href={h.competitorUrl} target="_blank" rel="noopener noreferrer" className="text-[11px] font-mono text-brand-600 hover:underline truncate max-w-[200px] inline-flex items-center gap-1">
                        {new URL(h.competitorUrl).pathname} <ExternalLink className="w-2.5 h-2.5 text-slate-300 shrink-0" />
                      </a>
                      <p className="text-[10px] text-slate-400">{h.competitorDomain}</p>
                    </td>
                    <td className="px-5 py-2.5 text-right text-xs text-slate-500 tabular-nums">{h.competitorWordCount?.toLocaleString() ?? "—"}</td>
                    <td className="px-5 py-2.5 text-right text-[11px] text-slate-400 tabular-nums">
                      {h.competitorLastmod ? new Date(h.competitorLastmod).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" }) : "—"}
                    </td>
                    <td className="px-5 py-2.5 text-right"><ConfidenceDot value={h.matchConfidence} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {filteredH2H.length > visibleCount && (
            <button onClick={() => setVisibleCount((c) => c + 25)} 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 ({filteredH2H.length - visibleCount} remaining)
            </button>
          )}
        </>
      )}
    </div>
  );
}
