import { useEffect, useState } from "react";
import { useApiRequest } from "../../utils/useApiRequest";
import Table from "../../components/Table/Table";
import { Grid } from "../../components/Grid/Grid";
import { Popover } from "../../components/PopOver/PopOver";
import { PopoverCustomModalOperation } from "../../components/PopOverCustomModalOperation/PopoverCustomModalOperation";
import { ArrowUturnDownIcon } from "@heroicons/react/24/outline";
import { getQuotaTableColumns, getQuotaTableRowData } from "./quotaTableUtils";
import { PaginationParameters } from "../../components/PaginationParameters/PaginationParameters";

export const QuotaClosed = () => {
  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [pagesTableData, setPagesTableData] = useState([]);
  const [publicParams, setPublicParams] = useState({
    start: null,
    end: null,
    search: null,
  });

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

  const { data: quotasDashboardData, refetch: quotasDashboardRefetch } =
    useApiRequest({
      api: "/product/web/api/v1/quota/quotas_dashboard?is_closed=true",
      method: "get",
      params: publicParams,
      queryKey: ["quotaClosedDashboard"],
    });

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

  useEffect(() => {
    if (pagesData?.results) {
      const tableData = pagesData.results.map((item: any, i: number) => {
        return getQuotaTableRowData(item, i, {
          pagesInfo,
          includeClosedDate: true,
          renderOperations: (item, index) => (
            <Popover key={index}>
              <PopoverCustomModalOperation
                method="patch"
                tooltipText="برگشت سهمیه"
                icon={<ArrowUturnDownIcon className="w-6 h-6 text-red-500" />}
                title="از برگشت سهمیه اطمینان دارید؟"
                api={`product/web/api/v1/quota/${item?.id}/activate/`}
                getData={handleUpdate}
                page="quota"
                access="Activate-Quota"
              />
            </Popover>
          ),
        });
      });
      setPagesTableData(tableData);
    }
  }, [pagesData]);

  return (
    <Grid container column className="gap-4 mt-2">
      <PaginationParameters
        title="بایگانی سهمیه ها"
        excelInfo={{
          link: `/product/excel/quota_excel/?closed=true&start=${
            publicParams.start || ""
          }&end=${publicParams.end || ""}&search=${publicParams.search || ""}`,
          title: "بایگانی سهمیه ها",
        }}
        getData={handleUpdate}
        onChange={(r) => {
          setPublicParams((prev) => ({ ...prev, ...(r as any) }));
          setPagesInfo((prev) => ({ ...prev, page: 1 }));
        }}
      />

      <Grid isDashboard>
        <Table
          isDashboard
          title="خلاصه اطلاعات"
          noPagination
          noSearch
          columns={[
            "تعداد کل سهمیه ها",
            "مجموع وزن سهمیه ها (کیلوگرم)",
            "مجموع وزن توزیع شده (کیلوگرم)",
            "مجموع وزن باقیمانده (کیلوگرم)",
            "مجموع وزن فروش رفته (کیلوگرم)",
            "مجموع وزن ورود به انبار (کیلوگرم)",
          ]}
          rows={[
            [
              quotasDashboardData?.quotas_summary?.total_quotas?.toLocaleString() ||
                0,
              quotasDashboardData?.quotas_summary?.total_amount?.toLocaleString() ||
                0,
              quotasDashboardData?.quotas_summary?.total_distributed?.toLocaleString() ||
                0,
              quotasDashboardData?.quotas_summary?.remaining_amount?.toLocaleString() ||
                0,
              quotasDashboardData?.quotas_summary?.sold_amount?.toLocaleString() ||
                0,
              quotasDashboardData?.quotas_summary?.inventory_received?.toLocaleString() ||
                0,
            ],
          ]}
        />
      </Grid>
      <Table
        className="mt-2"
        onChange={(e) => {
          setPagesInfo(e);
        }}
        count={pagesData?.count || 10}
        isPaginated
        noSearch
        title="بایگانی سهمیه ها"
        columns={getQuotaTableColumns({
          includeClosedDate: true,
          includeOperations: true,
        })}
        rows={pagesTableData}
      />
    </Grid>
  );
};
