"use client";

import { useState } from "react";
import { ChevronLeft, ChevronRight, Search, ExternalLink } from "lucide-react";
import { scoreToTier, TIER_COLORS, type ToxicityTier } from "@/lib/services/backlink-toxicity";

interface Backlink {
  id: string; sourceDomain: string; sourceUrl: string; targetUrl: string;
  anchorText: string | null; linkType: string | null; domainAuthority: number | null;
  relevanceScore: number | null; toxicityScore: number | null; qualityTier: string | null;
  toxicityReasons?: string[]; status: string; firstSeenAt: string;
}

/** Legacy qualityTier values from the old AI scorer
 *  (excellent/good/neutral/poor/toxic) re-bucket from the raw score so
 *  the table uses the same palette as the Toxic Panel. */
function resolveTier(score: number | null, tier: string | null): ToxicityTier {
  if (tier && (tier in TIER_COLORS)) return tier as ToxicityTier;
  return scoreToTier(score ?? 0);
}

interface Props {
  backlinks: Backlink[]; total: number; page: number; pages: number;
  onPageChange: (p: number) => void; onStatusFilter: (s: string) => void;
  onSortChange: (s: string) => void; onSearch: (d: string) => void;
  currentStatus: string; currentSort: string;
}

const STATUS_COLORS: Record<string, string> = { active: "bg-green-50 text-green-700", new: "bg-blue-50 text-blue-700", lost: "bg-red-50 text-red-700", disavowed: "bg-slate-100 text-slate-500" };
const TYPE_COLORS: Record<string, string> = { dofollow: "bg-green-50 text-green-700", nofollow: "bg-slate-100 text-slate-500", ugc: "bg-blue-50 text-blue-700", sponsored: "bg-purple-50 text-purple-700" };

export default function BacklinkTable({ backlinks, total, page, pages, onPageChange, onStatusFilter, onSortChange, onSearch, currentStatus, currentSort }: Props) {
  const [searchVal, setSearchVal] = useState("");

  return (
    <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      {/* Filters */}
      <div className="flex items-center gap-2 px-5 py-3 border-b border-slate-100 flex-wrap">
        <div className="relative">
          <Search className="w-3.5 h-3.5 text-slate-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
          <input value={searchVal} onChange={(e) => setSearchVal(e.target.value)} onKeyDown={(e) => e.key === "Enter" && onSearch(searchVal)}
            placeholder="Search domain..." className="pl-8 pr-3 py-1.5 text-xs border border-slate-200 rounded-lg w-44 focus:outline-none focus:ring-2 focus:ring-blue-500/40" />
        </div>
        {["all", "active", "new", "lost", "toxic", "disavowed"].map((s) => (
          <button key={s} onClick={() => onStatusFilter(s)} className={`px-2.5 py-1 text-[11px] font-semibold rounded-md capitalize ${currentStatus === s ? "bg-slate-900 text-white" : "text-slate-500 hover:bg-slate-100"}`}>{s}</button>
        ))}
        <select value={currentSort} onChange={(e) => onSortChange(e.target.value)} className="ml-auto text-xs border border-slate-200 rounded-lg px-2 py-1.5 bg-white">
          <option value="recent">Recent</option><option value="authority">Authority ↓</option><option value="toxicity">Toxicity ↓</option><option value="relevance">Relevance ↓</option>
        </select>
        <span className="text-[10px] text-slate-400">{total} links</span>
      </div>

      {/* Table */}
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead><tr className="border-b border-slate-100 bg-slate-50">
            <th className="text-left px-4 py-2 text-[10px] font-bold text-slate-500 uppercase">Source</th>
            <th className="text-left px-3 py-2 text-[10px] font-bold text-slate-500 uppercase">Anchor</th>
            <th className="text-center px-3 py-2 text-[10px] font-bold text-slate-500 uppercase">Type</th>
            <th className="text-right px-3 py-2 text-[10px] font-bold text-slate-500 uppercase">DA</th>
            <th className="text-center px-3 py-2 text-[10px] font-bold text-slate-500 uppercase">Toxicity</th>
            <th className="text-center px-3 py-2 text-[10px] font-bold text-slate-500 uppercase">Status</th>
          </tr></thead>
          <tbody className="divide-y divide-slate-100">
            {backlinks.map((b) => (
              <tr key={b.id} className="hover:bg-slate-50">
                <td className="px-4 py-2.5">
                  <a href={b.sourceUrl} target="_blank" rel="noopener noreferrer" className="text-xs font-semibold text-slate-800 hover:text-brand-600 flex items-center gap-1">
                    {b.sourceDomain} <ExternalLink className="w-2.5 h-2.5 text-slate-300" />
                  </a>
                  <p className="text-[10px] text-slate-400 truncate max-w-[200px]">{b.targetUrl?.replace(/^https?:\/\/[^/]+/, "") || "/"}</p>
                </td>
                <td className="px-3 py-2.5 text-xs text-slate-600 truncate max-w-[140px]">{b.anchorText || "—"}</td>
                <td className="px-3 py-2.5 text-center"><span className={`text-[9px] font-bold px-1.5 py-0.5 rounded ${TYPE_COLORS[b.linkType || ""] || TYPE_COLORS.nofollow}`}>{b.linkType || "—"}</span></td>
                <td className="px-3 py-2.5 text-right">
                  <span className={`text-xs font-bold ${(b.domainAuthority ?? 0) >= 50 ? "text-green-600" : (b.domainAuthority ?? 0) >= 20 ? "text-amber-600" : "text-red-600"}`}>{b.domainAuthority ?? "—"}</span>
                </td>
                <td className="px-3 py-2.5">
                  {/* Toxicity column — coloured dot at the tier colour
                      from backlink-toxicity.TIER_COLORS + score +
                      mini-bar. Shares the exact palette the Toxic
                      Panel uses so the two views visually agree. */}
                  {b.toxicityScore != null ? (() => {
                    const tier = resolveTier(b.toxicityScore, b.qualityTier);
                    const meta = TIER_COLORS[tier];
                    return (
                      <div className="w-20 mx-auto" title={`${tier} · ${b.toxicityScore}/100`}>
                        <div className="flex items-center gap-1.5">
                          <span className="inline-block w-1.5 h-1.5 rounded-full shrink-0" style={{ backgroundColor: meta.bar }} />
                          <div className="flex-1 h-1.5 bg-slate-100 rounded-full overflow-hidden">
                            <div className="h-full rounded-full" style={{ width: `${b.toxicityScore}%`, backgroundColor: meta.bar }} />
                          </div>
                          <span className="text-[9px] tabular-nums font-bold" style={{ color: meta.bar }}>{b.toxicityScore}</span>
                        </div>
                      </div>
                    );
                  })() : (
                    <p className="text-[9px] text-center text-slate-300">—</p>
                  )}
                </td>
                <td className="px-3 py-2.5 text-center"><span className={`text-[9px] font-bold px-1.5 py-0.5 rounded capitalize ${STATUS_COLORS[b.status] || STATUS_COLORS.active}`}>{b.status}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {pages > 1 && (
        <div className="flex items-center justify-between px-5 py-3 border-t border-slate-100">
          <button onClick={() => onPageChange(page - 1)} disabled={page <= 1} className="flex items-center gap-1 text-xs text-slate-500 hover:text-slate-700 disabled:opacity-30"><ChevronLeft className="w-3 h-3" /> Prev</button>
          <span className="text-xs text-slate-400">Page {page} of {pages}</span>
          <button onClick={() => onPageChange(page + 1)} disabled={page >= pages} className="flex items-center gap-1 text-xs text-slate-500 hover:text-slate-700 disabled:opacity-30">Next <ChevronRight className="w-3 h-3" /></button>
        </div>
      )}
    </div>
  );
}
