"use client";

import { parseAsInteger, useQueryState } from "nuqs";

import { useQuery } from "@tanstack/react-query";

import { ChevronLeft, ChevronRight, Search } from "lucide-react";

import { Input } from "@/components/ui/input";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
} from "@/components/ui/pagination";

import { createClient } from "@/utils/supabase/client";

import { Button } from "@/components/ui/button";

import AgentCardSkeleton from "./agent-card-skeleton";
import AgentCard from "./agent-card";
import { ChatFloatingButton } from "@/components/chat-floating-button";

const DATA_DISPLAY = 6;

export function AgentList() {
  const [searchFilter, setSearchFilter] = useQueryState("search", {
    defaultValue: "",
    throttleMs: 1000,
    shallow: false,
    history: "push",
  });

  const [paginationFilter, setPaginationFilter] = useQueryState(
    "page",
    parseAsInteger
      .withOptions({
        shallow: false,
        history: "push",
        scroll: false,
      })
      .withDefault(0)
  );

  const {
    data: agentsData,
    isLoading,
    error,
  } = useQuery({
    queryKey: ["agents", searchFilter, paginationFilter],
    queryFn: async ({ signal }) => {
      const supabase = createClient();

      const response = await supabase
        .from("agents")
        .select("*", { count: "exact" })
        .ilike("name", `%${searchFilter}%`)
        .order("id", { ascending: false })
        .range(
          paginationFilter * DATA_DISPLAY,
          paginationFilter * DATA_DISPLAY + DATA_DISPLAY - 1
        );

      return response;
    },
  });

  return (
    <>
      <section className="group pt-8 pb-10 min-h-[50vh] ">
        <div className="layout">
          <h1 className="mb-4 text-3xl font-bold text-foreground sm:text-4xl">
            Agents
          </h1>
          <div className="mb-8 flex flex-col sm:flex-row justify-between">
            <div className="relative">
              <Input
                aria-label="search"
                id="search"
                type="search"
                placeholder="Search..."
                className="min-w-64 pl-7"
                value={searchFilter}
                onChange={(e) => {
                  setPaginationFilter(0);
                  e.target.value === ""
                    ? setSearchFilter(null)
                    : setSearchFilter(e.target.value);
                }}
              />
              <Search className="absolute w-4 h-4 left-2 top-1/2 -translate-y-1/2 text-gray-300" />
            </div>
          </div>
          <ul className="grid gap-8 mb-10 sm:grid-cols-2 lg:grid-cols-3">
            {isLoading &&
              [...Array(6)].map((_, idx) => (
                <li key={idx}>
                  <AgentCardSkeleton />
                </li>
              ))}
            {agentsData &&
              agentsData.data?.map((agent) => (
                <AgentCard key={agent.name} data={agent} />
              ))}
          </ul>
          {agentsData ? (
            <Pagination>
              <PaginationContent>
                <PaginationItem>
                  <Button
                    variant={"outline"}
                    size={"icon"}
                    disabled={paginationFilter === 0}
                    onClick={() => setPaginationFilter((old) => old - 1)}
                  >
                    <ChevronLeft className="h-4 w-4" />
                  </Button>
                </PaginationItem>
                <p className="text-sm font-semibold text-gray-400">
                  Page {paginationFilter + 1} of{" "}
                  {agentsData.count
                    ? Math.ceil(agentsData.count / DATA_DISPLAY)
                    : 1}
                </p>
                <PaginationItem>
                  <Button
                    variant={"outline"}
                    size={"icon"}
                    disabled={
                      paginationFilter + 1 ===
                      Math.ceil(agentsData.count! / DATA_DISPLAY)
                    }
                    onClick={() => setPaginationFilter((old) => old + 1)}
                  >
                    <ChevronRight className="h-4 w-4" />
                  </Button>
                </PaginationItem>
              </PaginationContent>
            </Pagination>
          ) : null}
        </div>
      </section>
    </>
  );
}
