// =============================================================================
// HeadlineSift.com — Ranking Rule List Table
// =============================================================================
"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { useCallback, useTransition } from "react";
import { toggleRankingRuleStatus, deleteRankingRule } from "./actions";
import { cn } from "@/lib/utils";

export interface RankingRuleRow {
  id: string; categoryId: string; categoryName: string; categorySlug: string;
  countryId: string | null; countryName: string | null; countryCode: string | null;
  freshnessWeight: number; sourceTrustWeight: number; sourceCountWeight: number;
  officialSourceBoost: number; impactWeight: number;
  duplicatePenalty: number; lowConfidencePenalty: number; clickbaitPenalty: number;
  maxStories: number; status: string;
}

interface SelectOption { id: string; name: string; }

interface Props {
  rules: RankingRuleRow[];
  categoryFilter: string | null;
  statusFilter: string | null;
  categories: SelectOption[];
  editingId: string | null;
  onEdit: (id: string) => void;
  onAdd: () => void;
}

function StatusBadge({ status }: { status: string }) {
  const c: Record<string, string> = { ACTIVE: "bg-green-50 text-green-700", INACTIVE: "bg-slate-100 text-slate-600", DRAFT: "bg-amber-50 text-amber-700" };
  return <span className={cn("inline-flex items-center rounded-full px-2 py-0.5 text-2xs font-semibold uppercase tracking-wider", c[status] ?? "bg-slate-100")}>{status}</span>;
}

function WeightCell({ value, isPenalty }: { value: number; isPenalty?: boolean }) {
  return <span className={cn("text-xs tabular-nums", isPenalty ? "text-red-600" : "text-body")}>{value.toFixed(1)}</span>;
}

export default function RankingRuleTable({ rules, categoryFilter, statusFilter, categories, editingId, onEdit, onAdd }: Props) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [isPending, startTransition] = useTransition();

  const navigate = useCallback((overrides: Record<string, string | null>) => {
    const params = new URLSearchParams(searchParams.toString());
    for (const [k, v] of Object.entries(overrides)) {
      if (v === null) params.delete(k); else params.set(k, v);
    }
    params.delete("edit");
    startTransition(() => { router.push(`/admin/ranking-rules?${params.toString()}`); });
  }, [router, searchParams, startTransition]);

  const handleToggle = useCallback((id: string) => { startTransition(() => { toggleRankingRuleStatus(id); }); }, [startTransition]);

  const hasFilters = categoryFilter !== null || statusFilter !== null;

  return (
    <div className="space-y-4">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex flex-wrap items-center gap-3">
          <select value={categoryFilter ?? ""} onChange={(e) => navigate({ category: e.target.value || null })} className="input text-xs" style={{ maxWidth: "11rem" }}>
            <option value="">All categories</option>
            {categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
          <select value={statusFilter ?? ""} onChange={(e) => navigate({ status: e.target.value || null })} className="input text-xs" style={{ maxWidth: "7rem" }}>
            <option value="">All statuses</option>
            <option value="ACTIVE">Active</option>
            <option value="INACTIVE">Inactive</option>
            <option value="DRAFT">Draft</option>
          </select>
          {hasFilters && <span className="text-2xs text-body-muted">{rules.length} result{rules.length !== 1 ? "s" : ""}</span>}
        </div>
        <button type="button" onClick={onAdd} className="btn-primary shrink-0">
          <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 4.5v15m7.5-7.5h-15"/></svg>
          Add Rule
        </button>
      </div>

      {rules.length === 0 ? (
        <div className="card"><div className="flex flex-col items-center justify-center py-16 text-center"><span className="text-5xl">📈</span><h3 className="mt-4 text-lg font-semibold text-heading">No ranking rules yet</h3><p className="mt-2 text-sm text-body-muted">Add a ranking rule to configure scoring weights per category.</p></div></div>
      ) : (
        <div className="card overflow-x-auto p-0">
          <table className="w-full text-sm">
            <thead><tr className="border-b border-border bg-surface-secondary text-left">
              <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted">Category</th>
              <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted hidden sm:table-cell">Country</th>
              <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted hidden md:table-cell">Freshness</th>
              <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted hidden md:table-cell">Trust</th>
              <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted hidden lg:table-cell">Count</th>
              <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted hidden lg:table-cell">Official</th>
              <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted hidden lg:table-cell">Impact</th>
              <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted">Status</th>
              <th className="px-4 py-3 text-xs font-semibold uppercase tracking-wide text-body-muted w-28"><span className="sr-only">Actions</span></th>
            </tr></thead>
            <tbody className="divide-y divide-border">
              {rules.map((r) => (
                <tr key={r.id} className={cn("transition-colors hover:bg-surface-secondary", editingId === r.id && "bg-brand-50/50")}>
                  <td className="px-4 py-3"><span className="font-medium text-heading">{r.categoryName}</span></td>
                  <td className="px-4 py-3 hidden sm:table-cell">{r.countryName ? <span className="text-body">{r.countryName} <code className="text-2xs text-body-muted">{r.countryCode}</code></span> : <span className="text-body-muted/50 italic text-xs">Global</span>}</td>
                  <td className="px-4 py-3 hidden md:table-cell"><WeightCell value={r.freshnessWeight} /></td>
                  <td className="px-4 py-3 hidden md:table-cell"><WeightCell value={r.sourceTrustWeight} /></td>
                  <td className="px-4 py-3 hidden lg:table-cell"><WeightCell value={r.sourceCountWeight} /></td>
                  <td className="px-4 py-3 hidden lg:table-cell"><WeightCell value={r.officialSourceBoost} /></td>
                  <td className="px-4 py-3 hidden lg:table-cell"><WeightCell value={r.impactWeight} /></td>
                  <td className="px-4 py-3"><StatusBadge status={r.status} /></td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1">
                      <button type="button" onClick={() => onEdit(r.id)} className="rounded px-2 py-1 text-2xs font-medium text-brand-600 hover:bg-brand-50 transition-colors">Edit</button>
                      <button type="button" onClick={() => handleToggle(r.id)} disabled={isPending} className={cn("rounded px-2 py-1 text-2xs font-medium transition-colors", r.status === "ACTIVE" ? "text-amber-600 hover:bg-amber-50" : "text-green-600 hover:bg-green-50")}>{r.status === "ACTIVE" ? "Deactivate" : "Activate"}</button>
                      <DeleteButton rule={r} />
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="border-t border-border px-4 py-3 text-xs text-body-muted">{rules.length} {rules.length === 1 ? "rule" : "rules"}</div>
        </div>
      )}
    </div>
  );
}

function DeleteButton({ rule }: { rule: RankingRuleRow }) {
  const [isPending, startTransition] = useTransition();
  return (
    <button type="button" onClick={() => { if (!window.confirm(`Delete rule for "${rule.categoryName}"?`)) return; startTransition(() => { deleteRankingRule(rule.id); }); }} disabled={isPending} className="rounded px-2 py-1 text-2xs font-medium text-red-600 hover:bg-red-50 transition-colors">{isPending ? "Deleting…" : "Delete"}</button>
  );
}
