"use client";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import axios from "axios";
import { Alert, Pagination, Spinner } from "flowbite-react";
import { useRouter } from "next/navigation";
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 MacResellerAction from "./mac-reseller-actions";
import MacStatus from "./mac-status";

type props = {
  filterValue?: string | null;
};

const MacResellerList: FC<props> = ({ filterValue }) => {
  const [currentPage, setCurrentPage] = useState(1);
  const [pagination, setPagination] = useState<any>({});
  const router = useRouter();

  const onPageChange = (page: number) => setCurrentPage(page);

  let url = `/api/mac-resellers?page=${currentPage}`;
  const getMacResellers = async () => {
    const {
      data: { data },
      data: {
        data: { pagination },
      },
    } = await axios.get(filterValue ? `${url}&${filterValue}` : url);
    setPagination(pagination);
    return data?.data;
  };
  const {
    data: macResellers,
    isLoading,
    isError,
    refetch,
    error = {} as any,
  } = useQuery({
    queryKey: ["mac-reseller", { currentPage }],
    placeholderData: keepPreviousData,
    queryFn: () => getMacResellers(),
    retry: 0,
  });
  useEffect(() => {
    setCurrentPage(1);
    refetch();
  }, [filterValue]);

  const columns = [
    {
      header: "Reseller ID",
      accessorKey: "reseller_id",
    },
    {
      header: "MacReseller name",
      accessorKey: "name",
    },
    {
      header: "Phone",
      accessorKey: "phone",
    },
    {
      header: "Zone",
      accessorKey: "zone",
      cell: ({ row }: any) => {
        const mac = row.original;
        return <>{mac?.zone?.name}</>;
      },
    },
    {
      header: "Status",
      accessorKey: "status",
      cell: ({ row }: any) => {
        const mac = row.original;
        return <MacStatus mac={mac} />;
      },
    },
    {
      header: "Actions",
      cell: ({ row }: any) => {
        const macReseller = row.original;
        const mac_reseller_id: string = String(macReseller.id);
        const [isShow, setShow] = useState(false);
        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 && (
              <MacResellerAction macReseller={macReseller} isOpen={isShow} />
            )}
          </>
        );
      },
    },
  ];

  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>
      )}
      {macResellers !== undefined && (
        <div className="user-list pb-20 shadow-md">
          <div className="border-b">
            <DataTable data={macResellers} columns={columns} />
          </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">
                    {(pagination.current_page - 1) * 10 < 1
                      ? 1
                      : (pagination.current_page - 1) * 10}
                    - {pagination.current_page * 10}
                  </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 MacResellerList;
