"use client";
import getData from "@/utils/fetch";
import { useNumberFormat } from "@/utils/lib/helpers";
import { useQuery } from "@tanstack/react-query";
import React, { useEffect, useState } from "react";
import { toast } from "react-toastify";
import Spinner from "../spinner";
import { Filter } from "../forms/schema/filter";
import FilterForm from "../common/filter-form";
import CardSkeleton from "./card-skeleton-loader";

type ClientCount = {
  total_clients: number;
  active_clients: number;
  inactive_clients: number;
  new_clients_this_month: number;
};
export const clientFilter: Filter[] = [
  {
    name: "date_filter",
    type: "dropdown",
    placeholder: "This month",
    idName: "date_filter",
    initialData: [
      { name: "This month", id: 'this_month' },
      { name: "Last month", id: 'last_month' },
      { name: "This week", id: 'this_week' },
      { name: "Last week", id: 'last_week' },
      { name: "Last 15-day", id: 'last_15_days' },
      { name: "Today", id: 'today' },
      { name: "This year", id: 'this_year' },
      { name: "Last year", id: 'last_year' },
    ],
  },
];

const NewClientCards: React.FC = () => {
  const [filterValue, setFilter] = useState(null);
  let url = `/api/v1/dashboard-new-client-count`;
  if (filterValue) {
    url = `${url}?${filterValue}`
  }
  const getClientCount = async () => {
    const data = await getData(url);
    console.log(data, 'nc')
    if (!data?.success) {
      return toast.error(data);
    }
    return data?.data;
  };
  const { data: clients, isLoading, refetch, isFetching } = useQuery<ClientCount>({
    queryKey: ["new-client-count"],
    queryFn: () => getClientCount(),
    refetchOnWindowFocus: false,
    retry: 0,
  });
  useEffect(() => {
    if (!filterValue?.includes("#")) {
      refetch();
    }
  }, [filterValue]);
  const CountCard = ({ title, }: { title: string }) => (
    <>
      {isLoading ? (<CardSkeleton />) : (
        <div className="w-full h-full">
          <div className="flex font-medium">
            <div>
              {title}
            </div>
            <div className="mb-1">({useNumberFormat(clients?.new_clients)})</div>
          </div>
          <div>
            <div className={`text-lg font-bold text-gray-900  gap-2 w-full flex`}>
              <div className="flex-1">
                <div className=" font-normal text-base w-full">
                  <FilterForm className="p-0" schema={clientFilter} grids={1} setFilter={setFilter} searchButton={false} />
                </div>
              </div>
            </div>
            <div>
              {isFetching ? <Spinner size="sm" className="mt-4" /> : (
                <div className="mt-4">
                  <div>
                    <div className="flex justify-between">
                      <div className="text-green-600 font-medium">
                        Active: {useNumberFormat(clients?.active_clients)}
                      </div>
                      <div className="text-red-500 font-medium">
                        Inactive : {useNumberFormat(clients?.inactive_clients)}
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
  return (
    <>
      <div className=" p-3 shadow rounded">
        {<CountCard title="New clients" count={clients?.total_clients} />}
      </div>
    </>
  );
};

export default NewClientCards;
