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

interface QuotaDashboardByProduct {
  product_id: string;
  quotas_count: string;
  product_name: string;
  active_quotas_weight: string;
  closed_quotas_weight: string;
  total_quotas_weight: string;
  total_remaining_quotas_weight: string;
  total_remaining_distribution_weight: string;
  received_distribution_weight: string;
  given_distribution_weight: string;
  received_distribution_number: string;
  given_distribution_number: string;
  total_warehouse_entry: string;
  total_sold: string;
}

export const QuotaReportingProducts = () => {
  const [pagesTableData, setPagesTableData] = useState<any[][]>([]);

  const [publicParams, setPublicParams] = useState({
    start: null,
    end: null,
    search: null,
  });

  const { data: pagesData, refetch } = useApiRequest<QuotaDashboardByProduct[]>(
    {
      api: "/product/web/api/v1/quota/quotas_dashboard_by_product/",
      method: "get",
      params: { ...publicParams },
      queryKey: ["QuotaReportingAllProducts", publicParams],
    }
  );

  const navigate = useNavigate();

  const handleUpdate = () => {
    refetch();
  };

  useEffect(() => {
    if (pagesData && Array.isArray(pagesData)) {
      const tableData = pagesData.map(
        (item: QuotaDashboardByProduct, i: number) => {
          return [
            i + 1,
            item?.product_name,
            parseInt(item?.quotas_count)?.toLocaleString(),
            <ShowWeight key={i} weight={item?.active_quotas_weight} />,
            <ShowWeight key={i} weight={item?.closed_quotas_weight} />,
            <ShowWeight key={i} weight={item?.total_quotas_weight} />,
            <ShowWeight key={i} weight={item?.total_remaining_quotas_weight} />,
            <ShowWeight key={i} weight={item?.received_distribution_weight} />,
            <ShowWeight key={i} weight={item?.given_distribution_weight} />,
            parseInt(item?.received_distribution_number)?.toLocaleString(),
            parseInt(item?.given_distribution_number)?.toLocaleString(),
            <ShowWeight key={i} weight={item?.total_warehouse_entry} />,
            <ShowWeight key={i} weight={item?.total_sold} />,

            <Popover key={i}>
              <Tooltip title="جزئیات" position="right">
                <Button
                  variant="detail"
                  page="reporting_details"
                  access="Get-Product-Detail"
                  onClick={() => {
                    const path =
                      REPORTING +
                      "/quota/" +
                      item?.product_id +
                      "/" +
                      item?.product_name;
                    navigate({ to: path });
                  }}
                />
              </Tooltip>
            </Popover>,
          ];
        }
      );
      setPagesTableData(tableData);
    } else {
      setPagesTableData([]);
    }
  }, [pagesData]);

  return (
    <Grid container column className="gap-4 mt-2">
      <PaginationParameters
        title="محصولات"
        getData={handleUpdate}
        onChange={(r) => {
          setPublicParams((prev) => ({ ...prev, ...(r as any) }));
        }}
      />
      <Table
        className="mt-2"
        title="گزارش گیری"
        excelInfo={{
          link: "product/web/api/v1/quota/quotas_dashboard_by_product_excel",
          params: publicParams,
        }}
        columns={[
          "ردیف",
          "محصول",
          "تعداد کل سهمیه ها",
          "سهمیه های فعال",
          "سهمیه های بایگانی شده",
          "وزن کل سهمیه ها",
          "باقیمانده وزن سهمیه ها",
          "توزیع دریافتی",
          "توزیع ارسال شده",
          "تعداد توزیع دریافتی",
          "تعداد توزیع ارسالی",
          "کل وزن ورودی به انبار",
          "وزن فروش رفته",
          "عملیات",
        ]}
        rows={pagesTableData}
      />
    </Grid>
  );
};
