"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Row, Col, Card, Form, Button, Alert, Table, Badge } from "react-bootstrap";
import ZxdbBreadcrumbs from "@/app/zxdb/components/ZxdbBreadcrumbs";
import Pagination from "@/components/explorer/Pagination";

import type { PagedResult } from "@/types/zxdb";

type Genre = { id: number; name: string };

export default function GenresSearch({ initial, initialQ }: { initial?: PagedResult<Genre>; initialQ?: string }) {
  const router = useRouter();
  const [q, setQ] = useState(initialQ ?? "");
  const [data, setData] = useState<PagedResult<Genre> | null>(initial ?? null);
  const totalPages = useMemo(() => (data ? Math.max(1, Math.ceil(data.total / data.pageSize)) : 1), [data]);

  useEffect(() => {
    if (initial) setData(initial);
  }, [initial]);

  useEffect(() => {
    setQ(initialQ ?? "");
  }, [initialQ]);

  function submit(e: React.FormEvent) {
    e.preventDefault();
    const params = new URLSearchParams();
    if (q) params.set("q", q);
    params.set("page", "1");
    router.push(`/zxdb/genres?${params.toString()}`);
  }

  const buildHref = useCallback((p: number) => {
    const params = new URLSearchParams();
    if (q) params.set("q", q);
    params.set("page", String(p));
    return `/zxdb/genres?${params.toString()}`;
  }, [q]);

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

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

      <Row className="g-3">
        <Col lg={3}>
          <Card className="shadow-sm">
            <Card.Body>
              <Form className="d-flex flex-column gap-2" onSubmit={submit}>
                <Form.Group>
                  <Form.Label className="small text-secondary">Search</Form.Label>
                  <Form.Control placeholder="Search genres..." value={q} onChange={(e) => setQ(e.target.value)} />
                </Form.Group>
                <div className="d-grid">
                  <Button variant="primary" type="submit">Search</Button>
                </div>
              </Form>
            </Card.Body>
          </Card>
        </Col>

        <Col lg={9}>
          {data && data.items.length === 0 && <Alert variant="warning">No genres found.</Alert>}
          {data && data.items.length > 0 && (
            <Table striped hover className="align-middle">
              <caption className="visually-hidden">Genres search results</caption>
              <thead>
                <tr>
                  <th style={{ width: 120 }}>ID</th>
                  <th>Name</th>
                </tr>
              </thead>
              <tbody>
                {data.items.map((g) => (
                  <tr key={g.id}>
                    <td><Badge bg="light" text="dark">#{g.id}</Badge></td>
                    <td>
                      <Link href={`/zxdb/genres/${g.id}`}>{g.name}</Link>
                    </td>
                  </tr>
                ))}
              </tbody>
            </Table>
          )}
        </Col>
      </Row>

      <Pagination
        page={data?.page ?? 1}
        totalPages={totalPages}
        buildHref={buildHref}
        onPageChange={(p) => router.push(buildHref(p))}
      />
    </div>
  );
}
