import api from "../utils/api";
import Button from "../components/Button";
import CloseIcon from "../components/icons/CloseIcon";
import SpinIcon from "../components/icons/SpinIcon";
import MultySelect from "../components/MultySelect";
import SearchInput from "../components/SearchInput";
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { User } from "../types/User";
import { Client } from "../types/Client";
import { useDebounce } from "@uidotdev/usehooks";
import pluralize from "../utils/pluralize";

function ClientsPage() {
  const [limit, setLimit] = useState(10);
  const [search, setSearch] = useState<string | null>(null);

  const debouncedSearch = useDebounce(search, 500);

  const { data: me } = useQuery({
    queryKey: ["me"],
    queryFn: () => api.get("auth/me").json<User>(),
  });

  const { data: clients, isLoading } = useQuery({
    queryKey: ["clients", debouncedSearch],
    queryFn: () =>
      api
        .get("clients", {
          searchParams: debouncedSearch
            ? { search: debouncedSearch, limit }
            : {},
        })
        .json<Client[]>(),
    enabled: !!me,
  });

  const { data: count } = useQuery({
    queryKey: ["clients", "count", debouncedSearch],
    queryFn: () =>
      api
        .get(`clients/count`, {
          searchParams: debouncedSearch ? { search: debouncedSearch } : {},
        })
        .json<number>(),

    enabled: !!me,
  });

  function reset() {
    setSearch("");
  }

  return (
    <div className="flex flex-col gap-[1.667vw] h-full">
      <h1 className="title-l font-medium">Клиенты</h1>
      <div className="p-[1.389vw] rounded-[2.222vw] shadow-[0_4px_40px_0_rgba(15,16,17,0.05),0_2px_2px_0_rgba(15,16,17,0.05)] w-full">
        <div className="space-y-[1.111vw]">
          <div className="flex flex-col gap-[0.556vw] h-full">
            <SearchInput
              placeholder="Поиск клиентов"
              value={search || ""}
              onChange={(e) => setSearch(e.target.value)}
              setSearch={setSearch}
            />
            <div className="flex gap-[0.556vw]">
              <MultySelect
                data={[]}
                isGrid={false}
                placeholder={"Все встречи"}
                resetTitle={"Все встречи"}
                onSelect={() => console.log(1)}
              />
              <MultySelect
                data={[{ name: "сценарии", id: "1" }]}
                isGrid
                placeholder={"Все сценарии"}
                resetTitle={"Все сценарии"}
                onSelect={() => console.log(1)}
              />
            </div>
          </div>
          <div className="flex justify-between items-center">
            <p className="caption-m font-medium opacity-40">
              Найдено {count ? pluralize(count, "клиент") : "0 клиентов"}
            </p>
            <button className="flex gap-[0.278vw] items-center" onClick={reset}>
              <div className="size-[1.111vw] text-[#7D7D7D]">
                <CloseIcon />
              </div>
              <p className="text-[#7D7D7D] text-[0.972vw] font-medium">
                Сбросить все
              </p>
            </button>
          </div>
        </div>
      </div>
      <div className="space-y-[1.667vw]">
        {isLoading ? (
          <div className="size-[2.222vw] m-auto text-[#7B60F3] animate-spin">
            <SpinIcon />
          </div>
        ) : clients?.length ? (
          clients?.map(({ name }) => (
            <div key={name} className="aspace-y-[0.833vw]">
              <p className="caption-m font-medium opacity-40">{name}</p>
            </div>
          ))
        ) : (
          <div className="m-auto flex flex-col items-center gap-[1.111vw] w-[18.333vw] mt-[6.111vw]">
            <img src="/images/sad_ghost.png" alt="" className="w-[13.889vw]" />
            <div className="space-y-[0.556vw]">
              <p className="text-center font-medium title-m">Ничего не нашли</p>
              <p className="text-[#BDBDBD] caption-s font-medium">
                Попробуйте изменить параметры поиска
              </p>
            </div>
          </div>
        )}
      </div>
      {!!clients?.length && clients?.length === 0 && (
        <Button
          size="large"
          variant="primary"
          className="w-full"
          onClick={() => setLimit((prev) => prev + 10)}
          disabled={!!clients?.length && limit >= clients.length}
        >
          Показать еще
        </Button>
      )}
    </div>
  );
}

export default ClientsPage;
