import { useParams } from "@tanstack/react-router";
import { Grid } from "../../components/Grid/Grid";
import { useEffect, useState } from "react";
import { useApiRequest } from "../../utils/useApiRequest";
import Table from "../../components/Table/Table";
import Button from "../../components/Button/Button";
import { QuotaDistribution } from "./QuotaDistribution";
import { useModalStore } from "../../context/zustand-store/appStore";
import { Popover } from "../../components/PopOver/PopOver";
import { Tooltip } from "../../components/Tooltip/Tooltip";
import { formatJustDate, formatJustTime } from "../../utils/formatTime";
import { DeleteButtonForPopOver } from "../../components/PopOverButtons/PopOverButtons";
import { ShowWeight } from "../../components/ShowWeight/ShowWeight";
import {
  getQuotaDashboardColumns,
  getQuotaDashboardRowData,
} from "./quotaTableUtils";
import { QuotaDistributionOverview } from "./QuotaDistributionOverview";
import { useUserProfileStore } from "../../context/zustand-store/userStore";

export const QuotaDistributions = () => {
  const params = useParams({ strict: false });
  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/quota/${params?.code}/distributions_by_quota/`,
    method: "get",
    params: pagesInfo,
    queryKey: ["distributions_by_quota", pagesInfo],
  });

  const { profile } = useUserProfileStore();

  const { data: DashboardData, refetch: dashboardRefetch } = useApiRequest({
    api: `/product/web/api/v1/quota/${params?.code}/`,
    method: "get",
    queryKey: ["distributions_dashboard"],
  });

  useEffect(() => {
    if (pagesData?.results) {
      const tableData = pagesData.results.map((item: any, i: number) => {
        return [
          pagesInfo.page === 1
            ? i + 1
            : i + pagesInfo.page_size * (pagesInfo.page - 1) + 1,
          item?.distribution_id,
          `${formatJustDate(item?.create_date)} (${formatJustTime(
            item?.create_date
          )})`,
          item?.assigner_organization?.organization +
            " (" +
            item?.creator_info +
            ")",
          item?.assigned_organization?.organization,
          <ShowWeight
            key={DashboardData}
            weight={item?.weight}
            type={item?.sale_unit?.unit}
          />,
          <ShowWeight
            key={DashboardData}
            weight={item?.been_sold}
            type={item?.sale_unit?.unit}
          />,
          <ShowWeight
            key={DashboardData}
            weight={item?.warehouse_balance}
            type={item?.sale_unit?.unit}
          />,
          <ShowWeight
            key={DashboardData}
            weight={item?.warehouse_entry}
            type={item?.sale_unit?.unit}
          />,
          item?.description,
          <Popover key={DashboardData}>
            <Tooltip title="مشاهده توزیع" position="right">
              <Button
                size="small"
                page="quota_distributions"
                access="Edit-Distribution"
                variant="info"
                onClick={() => {
                  openModal({
                    title: "مشاهده توزیع",
                    isFullSize: true,
                    content: (
                      <QuotaDistributionOverview
                        item={item}
                        getData={handleUpdate}
                        code={params?.code}
                      />
                    ),
                  });
                }}
              />
            </Tooltip>

            {(profile?.role?.type?.key === "ADM" ||
              DashboardData?.assigned_to_me) && (
              <Button
                size="small"
                page="quota_distributions"
                access="Edit-Distribution"
                variant="edit"
                onClick={() => {
                  openModal({
                    title: "ویرایش توزیع",
                    content: (
                      <QuotaDistribution
                        item={item}
                        quota={item}
                        getData={handleUpdate}
                        code={params?.code}
                        remainWeight={
                          DashboardData?.remaining_weight + item?.weight
                        }
                      />
                    ),
                  });
                }}
              />
            )}

            {(profile?.role?.type?.key === "ADM" ||
              DashboardData?.assigned_to_me) && (
              <DeleteButtonForPopOver
                api={`product/web/api/v1/quota_distribution/${item?.id}`}
                getData={handleUpdate}
                page="quota_distributions"
                access="Delete-Distribution"
              />
            )}
          </Popover>,
        ];
      });
      setPagesTableData(tableData);
    }
  }, [pagesData]);

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

  return (
    <Grid container column className="gap-4">
      <Grid isDashboard>
        <Table
          isDashboard
          noPagination
          className="mt-2"
          onChange={(e) => {
            setPagesInfo(e);
          }}
          count={pagesData?.count || 10}
          isPaginated
          title="اطلاعات سهمیه"
          columns={getQuotaDashboardColumns()}
          rows={[getQuotaDashboardRowData(DashboardData || {})]}
        />
      </Grid>
      {(profile?.role?.type?.key === "ADM" ||
        DashboardData?.assigned_to_me) && (
        <Grid className="mt-8">
          <Button
            size="small"
            page="quota_distributions"
            access="Post-Distribution"
            variant="submit"
            onClick={() => {
              openModal({
                title: "ثبت توزیع",
                content: (
                  <QuotaDistribution
                    getData={handleUpdate}
                    code={params?.code}
                    remainWeight={DashboardData?.remaining_weight}
                    quota={DashboardData}
                  />
                ),
              });
            }}
          >
            ثبت توزیع
          </Button>
        </Grid>
      )}
      <Table
        className="mt-2"
        onChange={(e) => {
          setPagesInfo(e);
        }}
        count={pagesData?.count || 10}
        isPaginated
        title={`توزیع سهمیه `}
        columns={[
          "ردیف",
          "شناسه توزیع",
          "تاریخ ثبت",
          "توزیع کننده",
          "دریافت کننده",
          "وزن",
          "وزن فروش رفته",
          "مانده انبار",
          "ورودی به انبار",
          "توضیحات",
          "عملیات",
        ]}
        rows={pagesTableData}
      />
    </Grid>
  );
};
