import { useNavigate, useParams } from "@tanstack/react-router";
import { Grid } from "../../components/Grid/Grid";
import Table from "../../components/Table/Table";
import { useApiRequest } from "../../utils/useApiRequest";
import { useEffect, useState } from "react";
import { Popover } from "../../components/PopOver/PopOver";
import { Tooltip } from "../../components/Tooltip/Tooltip";
import Button from "../../components/Button/Button";
import { REPORTING } from "../../routes/paths";
import { getQuotaTableColumns, getQuotaTableRowData } from "./quotaTableUtils";

export const QuotaReportingProductDetails = () => {
  const params = useParams({ strict: false });

  const navigate = useNavigate();
  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [pagesTableData, setPagesTableData] = useState([]);

  const { data: pagesData } = useApiRequest({
    api: `/product/web/api/v1/product/${params?.itemid}/related_quotas/`,
    method: "get",
    params: pagesInfo,
    queryKey: ["QuotaReportingProductDetails", pagesInfo],
  });

  useEffect(() => {
    if (pagesData?.results) {
      const tableData = pagesData.results.map((item: any, i: number) => {
        return getQuotaTableRowData(item, i, {
          pagesInfo,
          renderOperations: (item, index) => (
            <Popover key={index}>
              <Tooltip title="جزئیات" position="right">
                <Button
                  variant="detail"
                  page="reporting_details"
                  access="Get-Product-Detail"
                  onClick={() => {
                    const path =
                      REPORTING +
                      "/distribution/" +
                      item?.id +
                      "/" +
                      params?.product;
                    navigate({ to: path });
                  }}
                />
              </Tooltip>
            </Popover>
          ),
        });
      });
      setPagesTableData(tableData);
    }
  }, [pagesData, pagesInfo, navigate, params?.product]);

  return (
    <Grid container column>
      <Table
        className="mt-2"
        onChange={(e) => {
          setPagesInfo(e);
        }}
        excelInfo={{
          link: "product/web/api/v1/product/${params?.itemid}/related_quotas_excel",
        }}
        count={pagesData?.count || 10}
        isPaginated
        showDates
        title={`سهمیه های ${params?.product}`}
        columns={getQuotaTableColumns({ includeOperations: true })}
        rows={pagesTableData}
      />
    </Grid>
  );
};
