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 { 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 { QuotaDistributionEntryInventory } from "../quota/QuotaDistributionEntryInventory";
import { DeleteButtonForPopOver } from "../../components/PopOverButtons/PopOverButtons";
import { useModalStore } from "../../context/zustand-store/appStore";
import { DocumentDownloader } from "../../components/DocumentDownloader/DocumentDownloader";

const formatGroupNames = (groups?: any[]) =>
  groups
    ?.map((group: any) =>
      group === "rural"
        ? "روستایی"
        : group === "industrial"
        ? "صنعتی"
        : "عشایری"
    )
    .join(", ");

const formatDeviceSaleType = (value?: string) =>
  value === "all"
    ? "بر اساس تعداد راس دام و وزن"
    : value === "weight"
    ? "بر اساس وزن"
    : value === "count"
    ? "بر اساس تعداد راس دام"
    : "-";

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

  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [pagesTableData, setPagesTableData] = useState<any[]>([]);
  const { openModal } = useModalStore();

  const { data: pagesData, refetch } = useApiRequest({
    api: `/warehouse/web/api/v1/inventory_entry/${params?.code}/my_entries_by_quota/`,
    method: "get",
    params: pagesInfo,
    queryKey: ["distributions_by_quota", pagesInfo],
  });

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

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

  const getRemainingWeight = (item: any) => {
    return (
      (Number(item?.weight) || 0) +
      (Number(DashboardData?.remaining_weight) || 0)
    );
  };

  useEffect(() => {
    if (pagesData?.results && DashboardData) {
      const tableData = pagesData.results.map((item: any, i: number) => {
        return [
          pagesInfo.page === 1
            ? i + 1
            : i + pagesInfo.page_size * (pagesInfo.page - 1) + 1,
          `${formatJustDate(item?.create_date)} (${formatJustTime(
            item?.create_date
          )})`,
          <ShowWeight
            key={i}
            weight={item?.weight}
            type={item?.distribution?.sale_unit}
          />,
          item?.lading_number,
          item?.delivery_address,
          <DocumentDownloader key={i} link={item?.document} />,
          item?.notes,

          <Popover key={i}>
            <Tooltip title="ویرایش" position="right">
              <Button
                size="small"
                variant="edit"
                page="inventory"
                access="Edit-Entry-Inventory"
                onClick={() => {
                  openModal({
                    title: "ویرایش ورودی به انبار ",
                    content: (
                      <QuotaDistributionEntryInventory
                        getData={handleUpdate}
                        code={params?.code}
                        item={item}
                        remainWeight={getRemainingWeight(item)}
                      />
                    ),
                  });
                }}
              />
            </Tooltip>
            <DeleteButtonForPopOver
              api={`warehouse/web/api/v1/inventory_entry/${item?.id}`}
              getData={handleUpdate}
              page="inventory"
              access="Delete-Entry-Inventory"
            />
          </Popover>,
        ];
      });
      setPagesTableData(tableData);
    }
  }, [pagesData, DashboardData]);

  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={[
            "شماره سهمیه",
            "وزن",
            "وزن باقیمانده سهمیه",
            "محصول",
            "واحد فروش",
            "نوع فروش",
            "گروه",
            "نوع فروش در دستگاه",
          ]}
          rows={[
            [
              DashboardData?.quota_id,
              <ShowWeight
                key={DashboardData?.id}
                weight={DashboardData?.inventory_received}
                type={DashboardData?.sale_unit?.unit}
              />,
              <ShowWeight
                key={DashboardData?.id}
                weight={DashboardData?.remaining_weight}
                type={DashboardData?.sale_unit?.unit}
              />,
              DashboardData?.product?.product || "-",
              DashboardData?.sale_unit?.unit || "-",
              DashboardData?.sale_type === "gov" ? "دولتی" : "آزاد",
              formatGroupNames(DashboardData?.group) || "-",
              formatDeviceSaleType(DashboardData?.pos_sale_type),
            ],
          ]}
        />
      </Grid>
      <Table
        className="mt-2"
        onChange={(e) => {
          setPagesInfo(e);
        }}
        excelInfo={{
          link: `warehouse/web/api/v1/inventory_entry/${params?.code}/my_entries_by_quota_excel`,
        }}
        count={pagesData?.count || 10}
        isPaginated
        title={`لیست ورود به انبار`}
        columns={[
          "ردیف",
          "تاریخ ثبت",
          "وزن",
          "شماره بارنامه",
          "محل دریافت",
          "سند",
          "توضیحات",
          "عملیات",
        ]}
        rows={pagesTableData}
      />
    </Grid>
  );
};
