import { useEffect, useState } from "react";
import { getJSONAuth } from "../../../api";
import { getToken } from "../../../admin/token";
import { useAdminT } from "../../../admin/useAdminT";

type Row = { id: number; query: string; createdAt: string };

export function AdminSearchLogs() {
  const t = useAdminT();
  const token = getToken();
  const [items, setItems] = useState<Row[]>([]);

  useEffect(() => {
    getJSONAuth<{ items: Row[] }>("/api/admin/search-logs?limit=300", token)
      .then((r) => setItems(Array.isArray(r.items) ? r.items : []))
      .catch(() => setItems([]));
  }, [token]);

  return (
    <div className="space-y-4">
      <h1 className="text-2xl font-bold">{t("adminSearchLogs")}</h1>
      <div className="overflow-x-auto rounded-2xl border border-ark-line">
        <table className="w-full text-sm">
          <thead className="bg-ark-panel text-left text-neutral-400">
            <tr>
              <th className="p-3">{t("adminSearchId")}</th>
              <th className="p-3">{t("adminSearchQuery")}</th>
              <th className="p-3">{t("adminSearchTime")}</th>
            </tr>
          </thead>
          <tbody>
            {items.map((x) => (
              <tr key={x.id} className="border-t border-ark-line">
                <td className="p-3 text-neutral-500">{x.id}</td>
                <td className="p-3 font-medium">{x.query}</td>
                <td className="p-3 text-neutral-400 whitespace-nowrap">
                  {x.createdAt}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {items.length === 0 ? (
        <p className="text-neutral-500 text-sm">{t("noResults")}</p>
      ) : null}
    </div>
  );
}
