"use client";
import Link from "next/link";
import { usePathname, useSearchParams, useRouter } from "next/navigation";
import { ChevronLeft, ChevronRight, ChevronsUpDown } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { pageSizes, updateQuery, type Pagination } from "@/lib/list-query";
export function useQueryUpdate() {
  const router = useRouter();
  const pathname = usePathname();
  const params = useSearchParams();
  return (updates: Record<string, string | null>) => {
    const query = updateQuery(params.toString(), updates);
    router.replace(query ? `${pathname}?${query}` : pathname, {
      scroll: false,
    });
  };
}
export function QueryTabs({
  items,
  active,
  appearance = "underline",
  clearListFilters = false,
  clearKeys = [],
}: {
  items: readonly { id: string; label: string }[];
  active: string;
  appearance?: "underline" | "segmented";
  clearListFilters?: boolean;
  clearKeys?: readonly string[];
}) {
  const pathname = usePathname();
  const params = useSearchParams();
  return (
    <nav
      aria-label="Page views"
      className={cn(
        "mb-4 flex max-w-full overflow-x-auto",
        appearance === "underline"
          ? "border-b"
          : "w-fit rounded-xl border border-input",
      )}
    >
      {items.map((item) => (
        <Link
          key={item.id}
          aria-current={active === item.id ? "page" : undefined}
          href={`${pathname}?${updateQuery(params.toString(), { ...(clearListFilters ? Object.fromEntries(["query", "name", "status", "online", "visibility", "protocol", "locationId", "locationName", "chargepointName", "userName", "idTag", "from", "to", "sort_by", "sort_order"].map((key) => [key, null])) : {}), ...Object.fromEntries(clearKeys.map((key) => [key, null])), tab: item.id, paginate_page: null })}`}
          scroll={false}
          className={cn(
            "shrink-0 px-4 py-3 text-sm font-medium",
            appearance === "underline"
              ? active === item.id
                ? "border-b-2 border-primary text-primary"
                : "text-muted-foreground"
              : active === item.id
                ? "bg-accent-foreground text-primary-foreground"
                : "text-accent-foreground",
          )}
        >
          {item.label}
        </Link>
      ))}
    </nav>
  );
}
export function SortHeading({
  label,
  value,
}: {
  label: string;
  value: string;
}) {
  const params = useSearchParams();
  const update = useQueryUpdate();
  const active = params.get("sort_by") === value;
  const currentOrder = params.get("sort_order") === "desc" ? "desc" : "asc";
  const order = active && currentOrder === "asc" ? "desc" : "asc";
  return (
    <th
      aria-sort={
        active ? (currentOrder === "asc" ? "ascending" : "descending") : "none"
      }
    >
      <button
        className="flex w-full items-center justify-between gap-4 whitespace-nowrap"
        onClick={() =>
          update({ sort_by: value, sort_order: order, paginate_page: null })
        }
      >
        {label}
        <ChevronsUpDown className="size-3 shrink-0 opacity-60" />
      </button>
    </th>
  );
}
export function PaginationControls({
  pagination,
  navigationEnabled = true,
  pageSizeEnabled = true,
  pageSizeKey = "paginate_limit",
}: {
  pagination: Pagination;
  navigationEnabled?: boolean;
  pageSizeEnabled?: boolean;
  pageSizeKey?: "paginate_limit" | "limit";
}) {
  const update = useQueryUpdate();
  const { page, pages, start, end, total, limit } = pagination;
  const startPage = Math.max(1, Math.min(page - 2, pages - 4));
  const numbers = Array.from(
    { length: Math.min(pages, 5) },
    (_, i) => startPage + i,
  );
  return (
    <div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-4 border-t px-5 py-4">
      <p className="text-sm text-muted-foreground">
        Showing {start} to {end} of {total} entries
      </p>
      <div className="ml-auto flex max-w-full flex-wrap items-center justify-end gap-4">
        {navigationEnabled && (
          <div className="flex flex-wrap items-center justify-end gap-2">
            <Button
              variant="outline"
              size="sm"
              disabled={page <= 1}
              onClick={() => update({ paginate_page: String(page - 1) })}
            >
              <ChevronLeft aria-hidden="true" />
              Previous
            </Button>
            <nav aria-label="Pagination" className="flex items-center gap-1">
              {numbers.map((n) => (
                <button
                  key={n}
                  aria-label={`Go to page ${n}`}
                  aria-current={page === n ? "page" : undefined}
                  className={cn(
                    "size-9 rounded-lg text-sm focus-visible:outline-2 focus-visible:outline-ring",
                    page === n ? "bg-accent text-primary" : "hover:bg-muted",
                  )}
                  onClick={() => update({ paginate_page: String(n) })}
                >
                  {n}
                </button>
              ))}
            </nav>
            <Button
              variant="outline"
              size="sm"
              disabled={page >= pages}
              onClick={() => update({ paginate_page: String(page + 1) })}
            >
              Next
              <ChevronRight aria-hidden="true" />
            </Button>
          </div>
        )}
        <label className="flex shrink-0 items-center gap-3 text-sm text-muted-foreground">
          Rows per page
          <select
            value={limit}
            disabled={!pageSizeEnabled}
            onChange={(event) =>
              update({ [pageSizeKey]: event.target.value, paginate_page: null })
            }
            className="h-10 min-w-20 rounded-lg border border-input bg-card px-3 text-foreground focus-visible:outline-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-50"
          >
            {pageSizes.map((size) => <option key={size} value={size}>{size}</option>)}
          </select>
        </label>
      </div>
    </div>
  );
}
