"use client";

import { useEffect, useMemo, useState } from "react";

type Item = { id: number; title: string; isXrated: number; machinetypeId: number | null; languageId: string | null };
type Paged<T> = { items: T[]; page: number; pageSize: number; total: number };

export default function LanguageDetailClient({ id }: { id: string }) {
  const [data, setData] = useState<Paged<Item> | null>(null);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const pageSize = 20;
  const totalPages = useMemo(() => (data ? Math.max(1, Math.ceil(data.total / data.pageSize)) : 1), [data]);

  async function load(p: number) {
    setLoading(true);
    try {
      const res = await fetch(`/api/zxdb/languages/${id}?page=${p}&pageSize=${pageSize}`, { cache: "no-store" });
      const json = (await res.json()) as Paged<Item>;
      setData(json);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    load(page);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [page]);

  return (
    <div className="container">
      <h1>Language {id}</h1>
      {loading && <div>Loading…</div>}
      {data && data.items.length === 0 && !loading && <div className="alert alert-warning">No entries.</div>}
      {data && data.items.length > 0 && (
        <div className="table-responsive">
          <table className="table table-striped table-hover align-middle">
            <thead>
              <tr>
                <th style={{ width: 80 }}>ID</th>
                <th>Title</th>
                <th style={{ width: 120 }}>Machine</th>
                <th style={{ width: 80 }}>Lang</th>
              </tr>
            </thead>
            <tbody>
              {data.items.map((it) => (
                <tr key={it.id}>
                  <td>{it.id}</td>
                  <td><a href={`/zxdb/entries/${it.id}`}>{it.title}</a></td>
                  <td>{it.machinetypeId ?? "-"}</td>
                  <td>{it.languageId ?? "-"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <div className="d-flex align-items-center gap-2 mt-2">
        <button className="btn btn-outline-secondary" onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={loading || page <= 1}>Prev</button>
        <span>Page {data?.page ?? page} / {totalPages}</span>
        <button className="btn btn-outline-secondary" onClick={() => setPage((p) => p + 1)} disabled={loading || (data ? data.page >= totalPages : false)}>Next</button>
      </div>
    </div>
  );
}
