import { useEffect, useState } from "react";
import { useModalStore } from "../context/zustand-store/appStore";
import { useApiRequest } from "../utils/useApiRequest";
import { Popover } from "../components/PopOver/PopOver";
import { Tooltip } from "../components/Tooltip/Tooltip";
import Button from "../components/Button/Button";
import { DeleteButtonForPopOver } from "../components/PopOverButtons/PopOverButtons";
import { Grid } from "../components/Grid/Grid";
import Table from "../components/Table/Table";
import { AddProductCategory } from "../partials/feed-input/AddProductCategory";

export const ProductsCategories = () => {
  const { openModal } = useModalStore();
  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [pagesTableData, setPagesTableData] = useState([]);

  const { data: pagesData, refetch } = useApiRequest({
    api: "/product/web/api/v1/category/",
    method: "get",
    params: pagesInfo,
    queryKey: ["productCategories", pagesInfo],
  });

  useEffect(() => {
    if (pagesData?.results) {
      const d = pagesData.results.map((item: any, i: number) => {
        return [
          pagesInfo.page === 1
            ? i + 1
            : i + pagesInfo.page_size * (pagesInfo.page - 1) + 1,
          item?.name,
          <Popover key={i}>
            <Tooltip title="ویرایش" position="right">
              <Button
                variant="edit"
                page="product_categories"
                access="Post-Product-Category"
                onClick={() => {
                  openModal({
                    title: "ویرایش دسته بندی",
                    content: (
                      <AddProductCategory item={item} getData={refetch} />
                    ),
                  });
                }}
              />
            </Tooltip>
            <DeleteButtonForPopOver
              page="product_categories"
              access="Post-Product-Category"
              api={`product/web/api/v1/category/${item?.id}/`}
              getData={refetch}
            />
          </Popover>,
        ];
      });
      setPagesTableData(d);
    }
  }, [pagesData, pagesInfo]);

  return (
    <Grid container column>
      <Grid>
        <Button
          size="small"
          page="product_categories"
          access="Post-Product-Category"
          variant="submit"
          onClick={() => {
            openModal({
              title: "ایجاد دسته بندی",
              content: <AddProductCategory getData={refetch} />,
            });
          }}
        >
          ایجاد دسته بندی
        </Button>
      </Grid>
      <Table
        className="mt-2"
        onChange={(e) => {
          setPagesInfo(e);
        }}
        count={pagesData?.count || 10}
        isPaginated
        title="دسته بندی ها"
        columns={["ردیف", "نام دسته بندی", "عملیات"]}
        rows={pagesTableData}
      />
    </Grid>
  );
};
