import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { manageProcessBuyReqService } from "../../services/manage-process-buy-req";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { IconButton, Tooltip, Typography } from "@mui/material";
import TuneIcon from "@mui/icons-material/Tune";
import { ProvinceManageOperationModalBuyReq } from "../province-manage-operation-modal-buy-req/ProvinceManageOperationModalBuyReq";
import { DRAWER, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { PaymentLinkModal } from "../province-manage-payment-link-modal/PaymentLinkModal";
import AttachmentIcon from "@mui/icons-material/Attachment";

export const ProvinceManageBuyReq = () => {
  const dispatch = useDispatch();
  const [tableData, setDataTable] = useState([]);
  const [data, setData] = useState([]);
  // const [anchorEl, setAnchorEl] = useState(null);

  const fetchdata = () => {
    dispatch(manageProcessBuyReqService()).then((r) => {
      setData(r.payload.data);
    });
  };

  useEffect(() => {
    fetchdata();
  }, []);

  // const handleClose = () => {
  //   setAnchorEl(null);
  // };
  useEffect(() => {
    const d = data?.map((item, i) => {
      const identity = item.killer
        ? `کشتارکن ${item?.type === "public" ? "عمومی" : "اختصاصی"} (${
            item?.killHouseForKiller?.killHouseName
          })`
        : "کشتارگاه";
      return [
        i + 1,
        identity,
        item.name,
        `${item?.killHouseOperator?.user?.fullname} (${item?.killHouseOperator?.user?.mobile})`,
        `${item?.systemAddress?.province?.name || ""} - ${
          item?.systemAddress?.city?.name || ""
        } - ${item?.systemAddress?.address || ""}`,
        item?.wageInfo?.totalAmount?.toLocaleString(),
        <Tooltip title="لینک پرداخت" placement="left-start" key={i}>
          <IconButton
            color="primary"
            onClick={() => {
              dispatch(
                OPEN_MODAL({
                  title: "لینک پرداخت بدهی",
                  content: <PaymentLinkModal item={item} />,
                })
              );
            }}
          >
            <AttachmentIcon />
          </IconButton>
        </Tooltip>,
        item?.allowPurchaseRequest?.limitation ? "فعال" : "غیر فعال",
        <>
          <Typography>
            {item?.maxKillLimit ? item.totalKillCapacity : "-"}
          </Typography>
        </>,
        <>
          <Typography>
            {item?.maxKillLimit ? `%${item.extraBarKillPercent}` : "-"}
          </Typography>{" "}
        </>,
        <>
          <Typography>
            {item?.inProvinceSellingLimitationPercent
              ? `%${item.inProvinceSellingLimitationPercent}`
              : "-"}
          </Typography>{" "}
        </>,
        <>
          <Typography>
            {item?.outProvinceSellingLimitationPercent
              ? `%${item.outProvinceSellingLimitationPercent}`
              : "-"}
          </Typography>
        </>,
        item?.quota ? "دارد" : "ندارد",
        item?.quota
          ? item?.quotaMaxKillLimit
            ? "بر اساس سقف کشتار"
            : item?.quotaRequest
            ? "بر اساس اعلام نیازها"
            : "بر اساس حجم از سقف کشتار"
          : "-",
        item?.governmentalQuota ? item?.governmentalQuota : "-",
        item?.quotaCustomQuantity ? item?.quotaCustomQuantity : "-",
        item?.maximumLoadVolumeIncrease || 0,
        item?.maximumLoadVolumeReduction || 0,
        item?.wareHouseRemaininggWeightLimitationStatus ? "فعال" : "غیر فعال",
        item?.wareHouseRemainingWeightLimitation
          ? `${item?.wareHouseRemainingWeightLimitation} کیلوگرم`
          : "-",
        item?.wareHouseRemainingPercentLimitationStatus ? "فعال" : "غیر فعال",
        item?.wareHouseRemainingPercentLimitation
          ? `%${item?.wareHouseRemainingPercentLimitation}`
          : "-",
        item?.wareHouseRemainingWeightArchivePercent
          ? `%${item?.wareHouseRemainingWeightArchivePercent}`
          : "-",
        <Tooltip title={"محدودیت پنل"} placement="left-start" key={i}>
          <IconButton
            aria-label="delete"
            color="primary"
            onClick={() => {
              // handleClose();
              dispatch(
                DRAWER({
                  right: !(window.innerWidth <= 700),
                  bottom: window.innerWidth <= 700,
                  title: "محدودیت پنل",
                  content: (
                    <ProvinceManageOperationModalBuyReq
                      item={item}
                      fetchdata={fetchdata}
                    />
                  ),
                })
              );
            }}
          >
            <TuneIcon />
          </IconButton>
        </Tooltip>,
      ];
    });
    setDataTable(d);
  }, [data]);

  return (
    <Grid>
      <ResponsiveTable
        paginated
        title="مجوز خرید"
        columns={[
          "ردیف",
          "ماهیت",
          "نام واحد",
          "نام و نام خانوادگی (تلفن)",
          "آدرس",
          "مبلغ بدهی (ریال)",
          "لینک پرداخت",
          "سقف بدهی",
          "محدودیت سقف کشتار",
          "درصد افزایش بار",
          "حداقل فروش داخل استان",
          "حداکثر فروش خارج استان",
          "الزام به خرید دولتی",
          "نوع الزام",
          "درصد الزام به خرید دولتی",
          "حجم الزام خرید از سقف کشتار",
          "حداکثر افزایش حجم ورود اطلاعات بار",
          "حداکثر کاهش حجم ورود اطلاعات بار",
          "محدودیت مانده انبار",
          "حداکثز وزن باقی مانده انبار",
          "محدودیت مانده روزانه انبار",
          "درصد وزن باقی مانده روزانه انبار",
          "حداکثر افت استاندارد لاشه",
          "عملیات",
        ]}
        data={tableData}
        customColors={[
          { name: "مجوز ثبت درخواست", color: "red" },
          { name: "محدودیت براساس بدهی", color: "red" },
          { name: "محدودیت پنل", color: "red" },
        ]}
      />
    </Grid>
  );
};
