import Link from "next/link";
import { listMagazines } from "@/server/repo";
import ZxdbBreadcrumbs from "@/app/zxdb/components/ZxdbBreadcrumbs";

export const metadata = { title: "ZXDB Magazines" };

// Depends on searchParams (?q=, ?page=). Force dynamic so each request renders correctly.
export const dynamic = "force-dynamic";

export default async function Page({
  searchParams,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
  const sp = await searchParams;
  const q = (Array.isArray(sp.q) ? sp.q[0] : sp.q) ?? "";
  const page = Math.max(1, Number(Array.isArray(sp.page) ? sp.page[0] : sp.page) || 1);

  const data = await listMagazines({ q, page, pageSize: 20 });
  const totalPages = Math.max(1, Math.ceil(data.total / data.pageSize));

  function makeHref(p: number) {
    const params = new URLSearchParams();
    if (q) params.set("q", q);
    params.set("page", String(p));
    return `/zxdb/magazines?${params.toString()}`;
  }

  return (
    <div>
      <ZxdbBreadcrumbs
        items={[
          { label: "ZXDB", href: "/zxdb" },
          { label: "Magazines" },
        ]}
      />

      <div className="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
        <div>
          <h1 className="mb-1">Magazines</h1>
          <div className="text-secondary">{data.total.toLocaleString()} results</div>
        </div>
      </div>

      <div className="row g-3">
        <div className="col-lg-3">
          <div className="card shadow-sm">
            <div className="card-body">
              <form className="d-flex flex-column gap-2" action="/zxdb/magazines" method="get">
                <div>
                  <label className="form-label small text-secondary">Search</label>
                  <input type="text" className="form-control" name="q" placeholder="Search magazines..." defaultValue={q} />
                </div>
                <div className="d-grid">
                  <button className="btn btn-primary" type="submit">Search</button>
                </div>
              </form>
            </div>
          </div>
        </div>

        <div className="col-lg-9">
          <div className="table-responsive">
            <table className="table table-striped table-hover align-middle">
              <caption className="visually-hidden">Magazines search results</caption>
              <thead>
                <tr>
                  <th>Title</th>
                  <th style={{ width: 140 }}>Language</th>
                  <th style={{ width: 120 }}>Issues</th>
                </tr>
              </thead>
              <tbody>
                {data.items.map((m) => (
                  <tr key={m.id}>
                    <td>
                      <Link href={`/zxdb/magazines/${m.id}`}>{m.title}</Link>
                    </td>
                    <td>{m.languageId}</td>
                    <td>
                      <span className="badge bg-secondary rounded-pill" title="Issues">
                        {m.issueCount}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {totalPages > 1 && (
        <nav className="mt-3" aria-label="Pagination">
          <ul className="pagination">
            <li className={`page-item ${page <= 1 ? "disabled" : ""}`}>
              <Link className="page-link" href={makeHref(Math.max(1, page - 1))}>Previous</Link>
            </li>
            <li className="page-item disabled">
              <span className="page-link">Page {page} of {totalPages}</span>
            </li>
            <li className={`page-item ${page >= totalPages ? "disabled" : ""}`}>
              <Link className="page-link" href={makeHref(Math.min(totalPages, page + 1))}>Next</Link>
            </li>
          </ul>
        </nav>
      )}
    </div>
  );
}
