import { Grid } from "../../components/Grid/Grid";
import { useEffect, useState } from "react";
import { useApiRequest } from "../../utils/useApiRequest";
import Table from "../../components/Table/Table";
import { formatJustDate, formatJustTime } from "../../utils/formatTime";
import { ShowWeight } from "../../components/ShowWeight/ShowWeight";
import { Popover } from "../../components/PopOver/PopOver";
import { Tooltip } from "../../components/Tooltip/Tooltip";
import Button from "../../components/Button/Button";
import { QuotaDistribution } from "./QuotaDistribution";
import { DeleteButtonForPopOver } from "../../components/PopOverButtons/PopOverButtons";
import { useModalStore } from "../../context/zustand-store/appStore";
import { PaginationParameters } from "../../components/PaginationParameters/PaginationParameters";

export const QuotaAllDistributions = () => {
  const [params, setParams] = useState({ page: 1, page_size: 10 });
  const [pagesTableData, setPagesTableData] = useState([]);
  const { openModal } = useModalStore();

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

  const { data: apiData, refetch } = useApiRequest({
    api: `/product/web/api/v1/quota_distribution/my_distributions/`,
    method: "get",
    params: { param: "assigner", ...params, ...publicParams },
    queryKey: ["my_distributions", params],
  });

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

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

  useEffect(() => {
    if (apiData?.results) {
      const tableData = apiData.results.map((item: any, i: number) => {
        return [
          params.page === 1
            ? i + 1
            : i + params.page_size * (params.page - 1) + 1,
          item?.distribution_id,
          item?.quota?.quota_id,
          item?.quota?.product?.product,
          `${formatJustDate(item?.create_date)} (${formatJustTime(
            item?.create_date
          )})`,
          `${item?.assigner_organization?.organization} (${item?.creator_info})`,
          item?.assigned_organization?.organization,
          <ShowWeight
            key={i}
            weight={item?.weight}
            type={item?.quota?.sale_unit?.unit}
          />,
          <ShowWeight
            key={i}
            weight={item?.distributed}
            type={item?.quota?.sale_unit?.unit}
          />,
          <ShowWeight
            key={i}
            weight={item?.remaining_weight}
            type={item?.quota?.sale_unit?.unit}
          />,
          <ShowWeight
            key={i}
            weight={item?.been_sold}
            type={item?.quota?.sale_unit?.unit}
          />,
          <ShowWeight
            key={i}
            weight={item?.warehouse_balance}
            type={item?.quota?.sale_unit?.unit}
          />,
          <ShowWeight
            key={i}
            weight={item?.warehouse_entry}
            type={item?.quota?.sale_unit?.unit}
          />,
          item?.description,
          <Popover key={i}>
            <Tooltip title="ویرایش" position="right">
              <Button
                size="small"
                page="quota_distributions"
                access="Edit-Distribution"
                variant="edit"
                onClick={() => {
                  openModal({
                    title: "ویرایش توزیع",
                    content: (
                      <QuotaDistribution
                        item={item}
                        quota={item}
                        getData={handleUpdate}
                        code={item?.quota?.id}
                        remainWeight={item?.remaining_weight}
                      />
                    ),
                  });
                }}
              />
            </Tooltip>
            <DeleteButtonForPopOver
              api={`product/web/api/v1/quota_distribution/${item?.id}`}
              getData={handleUpdate}
              page="quota_distributions"
              access="Delete-Distribution"
            />
          </Popover>,
        ];
      });
      setPagesTableData(tableData);
    }
  }, [apiData]);

  return (
    <Grid container column className="gap-4 mt-2">
      <PaginationParameters
        title="لیست توزیع"
        excelInfo={{
          link: `/product/excel/quota_excel/?distributions=true&start=${
            publicParams.start || ""
          }&end=${publicParams.end || ""}&search=${publicParams.search || ""}`,
          title: "لیست توزیع",
        }}
        getData={handleUpdate}
        onChange={(r) => {
          setPublicParams((prev) => ({ ...prev, ...(r as any) }));
          setParams((prev) => ({ ...prev, page: 1 }));
        }}
        filters={[
          {
            api: "/product/web/api/v1/product/",
            selectedKeys: [publicParams.product_id || ""],
            onChange: (keys) => {
              setPublicParams((prev) => ({
                ...prev,
                product_id: keys[0] as string,
              }));
              setParams((prev) => ({ ...prev, page: 1 }));
            },
            title: "محصول",
            size: "small",
          },
        ]}
      />

      <Grid isDashboard>
        <Table
          isDashboard
          title="خلاصه اطلاعات"
          noPagination
          noSearch
          columns={[
            "تعداد کل توزیع ها",
            "مجموع وزن توزیع شده (کیلوگرم)",
            "مجموع وزن باقیمانده (کیلوگرم)",
            "مجموع وزن فروش رفته (کیلوگرم)",
            "مجموع وزن ورود به انبار (کیلوگرم)",
          ]}
          rows={[
            [
              quotasDashboardData?.quotas_summary?.distribution_number?.toLocaleString() ||
                0,
              quotasDashboardData?.quotas_summary?.total_distributed?.toLocaleString() ||
                0,
              quotasDashboardData?.quotas_summary?.dist_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) => {
          setParams(e);
        }}
        noSearch
        count={apiData?.count || 10}
        title={`لیست توزیع`}
        isPaginated
        columns={[
          "ردیف",
          "شناسه توزیع",
          "شناسه سهمیه",
          "محصول",
          "تاریخ ثبت",
          "توزیع کننده",
          "دریافت کننده",
          "وزن",
          "وزن توزیع شده",
          "وزن باقیمانده",
          "وزن فروش رفته",
          "مانده انبار",
          "ورودی به انبار",
          "توضیحات",
          "عملیات",
        ]}
        rows={pagesTableData}
      />
    </Grid>
  );
};
