"use client";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import axios from "axios";
import { Alert, Pagination, Spinner } from "flowbite-react";
import { FC, useEffect, useState } from "react";
import { BsThreeDots } from "react-icons/bs";
import { HiInformationCircle } from "react-icons/hi";
import DataTable from "../dataTable/data-table-fb";
import ClientAction from "./client-actions";
import ClientPaymentInfo from "./client-blling-paymet";
import ClientNameInfo from "./client-id-name-phone";
import ClientPackageInfo from "./client-package";
import ClientStatus from "./client-status";
import ClientZoneInfo from "./client-zone-address";

type props = {
  filterValue?: string | null;
};
const ClientList: FC<props> = ({ filterValue }) => {
  const [currentPage, setCurrentPage] = useState<any>(1);
  const [pagination, setPagination] = useState<any>({});
  const [isOpen, setOpen] = useState(false);
  const hideDropdown = () => {
    console.log("click");
    setOpen(false);
  };

  let url = `/api/clients?page=${currentPage}`;

  const onPageChange = (page: number) => {
    setCurrentPage(page);
  };
  const getClients = async () => {
    const {
      data: { data },
      data: {
        data: { pagination },
      },
    } = await axios.get(filterValue ? `${url}&${filterValue}` : url);
    setPagination(pagination);
    return data?.data;
  };
  const {
    data: clients,
    isLoading,
    isError,
    refetch,
    error = {} as any,
  } = useQuery({
    queryKey: ["clients", { currentPage }],
    placeholderData: keepPreviousData,
    queryFn: () => getClients(),
    retry: 0,
  });

  useEffect(() => {
    setCurrentPage(1);
    refetch();
  }, [filterValue]);
  const columns = [
    {
      header: "ID/Name/Phone",
      accessorKey: "name",
      cell: ({ row }: any) => {
        const client = row.original;
        return <ClientNameInfo client={client} />;
      },
    },
    {
      header: "Zone/Address/Network",
      accessorKey: "address",
      cell: ({ row }: any) => {
        const client = row.original;
        return <ClientZoneInfo client={client} />;
      },
    },
    {
      header: "connection/Package",
      accessorKey: "package",
      cell: ({ row }: any) => {
        const client = row.original;
        return <ClientPackageInfo client={client} />;
      },
    },
    {
      header: "Bill/Payment",
      accessorKey: "payment_deadline",
      cell: ({ row }: any) => {
        const client = row.original;
        return <ClientPaymentInfo client={client} />;
      },
    },
    {
      header: "Status",
      accessorKey: "status",
      cell: ({ row }: any) => {
        const client = row.original;
        return <ClientStatus client={client} />;
      },
    },
    {
      header: "Actions",
      id: "testing",
      cell: ({ row }: any) => {
        const client = row.original;
        const [isShow, setShow] = useState(isOpen);
        return (
          <>
            <div
              onClick={() => setShow((show) => !show)}
              className="cursor-pointer align-center text-center px-3 py-2 bg-gray-200 rounded-md w-10"
            >
              {<BsThreeDots />}
            </div>
            {isShow && <ClientAction client={client} isOpen={isShow} />}
          </>
        );
      },
    },
  ];
  const startIndex = (pagination.current_page - 1) * 10 || 1;
  const endIndex =
    startIndex + 9 > pagination.total ? pagination.total : startIndex + 9;

  return (
    <>
      {isLoading && (
        <div className="text-center">
          <Spinner
            aria-label="Center-aligned spinner example"
            className="mt-20"
            size="xl"
          />
        </div>
      )}
      {isError && (
        <Alert color="failure" icon={HiInformationCircle}>
          <span className="font-medium">Info alert!</span>
          {error?.response?.data?.error?.message}
        </Alert>
      )}
      {clients !== undefined && (
        <div className="user-list pb-20 shadow-md">
          <div className="border-b">
            <DataTable data={clients} columns={columns} fixedHeader={true} />
          </div>

          <div className="flex justify-between overflow-x-auto">
            <div className="flex">
              <Pagination
                className="ml-2 mt-2"
                layout="navigation"
                currentPage={currentPage}
                totalPages={pagination.total_pages || 0}
                onPageChange={onPageChange}
                showIcons
                nextLabel=""
                previousLabel=""
              />
              <div className="ml-2 mt-5">
                <p className="text-gray-500">
                  Showing
                  <span className="ml-2 mr-1 mt-1 text-gray-900">
                    {startIndex} - {endIndex}
                  </span>
                  of <span className="text-gray-900">{pagination.total}</span>
                </p>
              </div>
            </div>
            <Pagination
              currentPage={currentPage}
              totalPages={pagination.total_pages || 0}
              onPageChange={onPageChange}
              className="mr-2 mt-2 text-blue-900 sm:justify-end"
              showIcons
              color="blue"
            />
          </div>
        </div>
      )}
    </>
  );
};
export default ClientList;
