"use client";

import Image from "next/image";
import Link from "next/link";

import { parseAsInteger, useQueryState } from "nuqs";

import { motion } from "framer-motion";

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

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

import PostgrestError from "@/lib/config";
import { cn } from "@/lib/utils";

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

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

import AgentCard from "./agent-card";
import AgentCardSkeleton from "./agent-card-skeleton";

const DATA_DISPLAY = 6;
const ease = [0.16, 1, 0.3, 1];

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
        );

      console.log(response);
      if (response.error) throw new PostgrestError(response.error);

      return response;
    },
  });

  return (
    <>
      <motion.h1
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.8, ease }}
        className="mb-4 text-3xl font-bold text-foreground sm:text-4xl"
      >
        Agents
      </motion.h1>
      <motion.div
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.8, ease }}
        className="mb-8 flex flex-col sm:flex-row gap-3 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>
        <Link
          href={`/agents/create`}
          className={cn(
            buttonVariants({ variant: "default" }),
            "w-full sm:w-auto text-background flex gap-2"
          )}
        >
          <BadgePlus className="h-6 w-6" />
          Create new Agent
        </Link>
      </motion.div>
      {agentsData && agentsData.data.length === 0 && (
        <div className="flex flex-col justify-center items-center ">
          <figure className="relative w-full sm:w-1/2 h-72 sm:h-96 mb-6">
            <Image
              className="object-cover"
              src="/empty-data.jpg"
              fill={true}
              alt="Empty data"
            />
          </figure>
          <h1 className="text-xl font-bold">No data found</h1>
        </div>
      )}
      {isLoading ? (
        <motion.ul
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8, ease }}
          className="grid gap-8 mb-10 sm:grid-cols-2 lg:grid-cols-3"
        >
          {[...Array(6)].map((_, idx) => (
            <li key={idx}>
              <AgentCardSkeleton />
            </li>
          ))}
        </motion.ul>
      ) : (
        <ul className="grid gap-8 mb-10 sm:grid-cols-2 lg:grid-cols-3">
          {agentsData &&
            agentsData.data?.map((agent, idx) => (
              <AgentCard key={agent.name} data={agent} idx={idx} />
            ))}
        </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={
                  agentsData.count === 0
                    ? true
                    : paginationFilter + 1 ===
                      Math.ceil(agentsData.count! / DATA_DISPLAY)
                }
                onClick={() => setPaginationFilter((old) => old + 1)}
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            </PaginationItem>
          </PaginationContent>
        </Pagination>
      ) : null}
    </>
  );
}
