"use client";

import { useState, useMemo } from "react";
import type { EndpointDetail } from "../lib/types";
import { STATUS_COLORS, STATUS_LABELS } from "./StatusChart";

type SortKey = "method" | "path" | "status";
type SortDir = "asc" | "desc";

const STATUS_ORDER: Record<string, number> = {
  unused: 0,
  used: 1,
};

function StatusBadge({ status }: { status: string }) {
  return (
    <span
      className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium"
      style={{ backgroundColor: STATUS_COLORS[status] + "26", color: STATUS_COLORS[status] || "#94a3b8" }}
    >
      {STATUS_LABELS[status] || status}
    </span>
  );
}

export function EndpointTable({ details }: { details: EndpointDetail[] }) {
  const [filter, setFilter] = useState<string>("all");
  const [sortKey, setSortKey] = useState<SortKey>("status");
  const [sortDir, setSortDir] = useState<SortDir>("asc");

  const filtered = useMemo(() => {
    let rows = details;
    if (filter !== "all") {
      rows = rows.filter((d) => d.status === filter);
    }
    return [...rows].sort((a, b) => {
      let cmp = 0;
      if (sortKey === "status") {
        cmp = (STATUS_ORDER[a.status] ?? 99) - (STATUS_ORDER[b.status] ?? 99);
      } else {
        cmp = (a[sortKey] ?? "").localeCompare(b[sortKey] ?? "");
      }
      return sortDir === "asc" ? cmp : -cmp;
    });
  }, [details, filter, sortKey, sortDir]);

  function handleSort(key: SortKey) {
    if (sortKey === key) {
      setSortDir(sortDir === "asc" ? "desc" : "asc");
    } else {
      setSortKey(key);
      setSortDir("asc");
    }
  }

  const arrow = (key: SortKey) => {
    if (sortKey !== key) return "";
    return sortDir === "asc" ? " \u25B2" : " \u25BC";
  };

  const statuses = ["all", "used", "unused"];

  return (
    <div>
      <div className="mb-4 flex flex-wrap gap-2">
        {statuses.map((s) => (
          <button
            key={s}
            onClick={() => setFilter(s)}
            className={`rounded-full px-3 py-1 text-xs font-medium transition-colors cursor-pointer ${
              filter === s
                ? "bg-accent text-text-primary border border-accent"
                : "bg-raised text-text-secondary hover:text-text-primary border border-border"
            }`}
          >
            {s === "all" ? "All" : STATUS_LABELS[s]}
            {s !== "all" && ` (${details.filter((d) => d.status === s).length})`}
          </button>
        ))}
      </div>

      <div className="bg-surface border border-border rounded-lg overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="text-left text-xs uppercase tracking-wider text-text-secondary border-b border-border">
                <th className="cursor-pointer px-4 py-3 font-medium" onClick={() => handleSort("method")}>
                  Method{arrow("method")}
                </th>
                <th className="cursor-pointer px-4 py-3 font-medium" onClick={() => handleSort("path")}>
                  Path{arrow("path")}
                </th>
                <th className="cursor-pointer px-4 py-3 font-medium" onClick={() => handleSort("status")}>
                  Status{arrow("status")}
                </th>
                <th className="px-4 py-3 font-medium">Dead Functions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((ep, i) => (
                <tr
                  key={`${ep.method}-${ep.path}-${i}`}
                  className="border-b border-border/50 hover:bg-raised/50 transition-colors"
                >
                  <td className="px-4 py-3 text-sm">
                    <span className="font-mono text-xs font-semibold">{ep.method}</span>
                  </td>
                  <td className="px-4 py-3 text-sm">
                    <span className="font-mono text-xs">{ep.path}</span>
                    <span className="ml-2 text-xs text-text-secondary">
                      {ep.file}:{ep.line}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-sm">
                    <StatusBadge status={ep.status} />
                  </td>
                  <td className="px-4 py-3 text-sm text-text-secondary">
                    {ep.dead_functions.length > 0 && (
                      <span className="text-warning">{ep.dead_functions.length} functions</span>
                    )}
                  </td>
                </tr>
              ))}
              {filtered.length === 0 && (
                <tr>
                  <td colSpan={4} className="px-4 py-8 text-center text-text-secondary text-sm">
                    No endpoints match this filter.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
