"use client";
import { Product } from "@/interfaces/Product";
import { usePermission } from "@/utils/auth/permission";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import axios from "axios";
import { Alert, Checkbox, Pagination, Spinner } from "flowbite-react";
import { BaseSyntheticEvent, FC, useState } from "react";
import { HiInformationCircle } from "react-icons/hi";
import DataTable from "../dataTable/data-table-fb";
import ProductDelete from "./product-delete";
import ProductEdit from "./product-edit";

type props = {
  setProductIds: Function;
  productIds: string[];
};
const ProductList: FC<props> = ({ setProductIds, productIds }) => {
  const [pagination, setPagination] = useState<any>();
  const [currentPage, setCurrentPage] = useState(1);
  const onPageChange = (page: number) => setCurrentPage(page);

  const {
    data: products,
    isLoading,
    isError,
    error,
  } = useQuery({
    queryKey: ["products", { currentPage }],
    placeholderData: keepPreviousData,
    queryFn: async () => {
      const {
        data: { data },
        data: {
          data: { pagination },
        },
      } = await axios.get(`/api/products?page=${currentPage}`);
      setPagination(pagination);
      return data?.data;
    },
    retry: 0,
  });
  const getIds = (event: BaseSyntheticEvent) => {
    const productId = event.target.value;
    const isChecked = event.target.checked;
    if (!isChecked) {
      setProductIds((prev: string[]) =>
        prev.filter((product: string) => product !== productId)
      );
    } else {
      setProductIds((prev: string[]) => [...prev, productId]);
    }
  };

  const selectAll = (table: any) => {
    let selectedId: string[] = table
      .getRowModel()
      .rows.map((row: any) => row.getValue("id"));
    if (productIds.length > 0) {
      selectedId = [];
    }
    setProductIds(selectedId);
  };

  if (isLoading) {
    return (
      <div className="mt-16 text-center">
        <Spinner aria-label="Center-aligned spinner example" size="xl" />
      </div>
    );
  }
  if (isError) {
    return (
      <Alert color="failure" icon={HiInformationCircle}>
        <span className="font-medium">Info alert!</span>{" "}
        {error?.response?.data?.error?.message}{" "}
      </Alert>
    );
  }

  const columns = [
    {
      header: ({ table }: any) => (
        <Checkbox
          onChange={() => selectAll(table)}
          className="cursor-pointer"
          checked={productIds.length > 0}
        />
      ),
      accessorKey: "id",
      cell: ({ row }: any) => (
        <div className="px-1">
          <Checkbox
            id={`product-id-${row.getValue("id")}`}
            value={row.getValue("id")}
            className="cursor-pointer"
            onChange={getIds}
            checked={productIds.includes(row.getValue("id"))}
          />
        </div>
      ),
    },
    {
      header: "Name",
      accessorKey: "name",
    },
    {
      header: "Technology",
      accessorKey: "technology",
    },
    {
      header: "Product ID",
      accessorKey: "productID",
    },
    {
      header: "Price",
      accessorKey: "price",
    },
    {
      header: "Actions",
      id: "testing",
      cell: ({ row }: any) => {
        const product: Product = row.original;
        return (
          <>
            <div className="-mt-2 flex">
              <div className="mr-2">
                {usePermission("products.edit") && <ProductEdit {...product} />}
              </div>
              {usePermission("products.delete") && (
                <ProductDelete productIds={[product.id as string]} />
              )}
            </div>
          </>
        );
      },
    },
  ];
  return (
    <>
      {products !== undefined && (
        <div className="user-list pb-20 shadow-md">
          <div className="border-b">
            <DataTable data={products} 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 ProductList;
