import {
  Button,
  IconButton,
  Popover,
  TextField,
  Typography,
} from "@mui/material";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { getPoultryRequestsTotalQuantityService } from "../../../city/services/get-poultry-requests-total-quantity";
import { provinceCreateAutoAllocationService } from "../../services/province-create-auto-allocation";
import { provinceEditAutoAllocationService } from "../../services/province-edit-auto-allocation";
import { provinceGetAutoAllocationsService } from "../../services/province-get-auto-allocations";
import DeleteIcon from "@mui/icons-material/Delete";
import AddIcon from "@mui/icons-material/Add";
import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { ProvinceAddBuyerAutoAllocation } from "../province-add-buyer-auto-allocation/ProvinceAddBuyerAutoAllocation";
import { provinceDeleteAutoAllocationService } from "../../services/province-delete-auto-allocation";
import { provinceAddAutoAllocationService } from "../../services/province-add-auto-allocation";
import PrintIcon from "@mui/icons-material/Print";
import { provinceSubmitFinalAutoAllocationsService } from "../../services/province-submit-final-auto-allocations";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment/moment";
import { ProvinceAutoSelectOptions } from "../province-auto-select-options/ProvinceAutoSelectOptions";

export const ProvinceAutoAllocationRequests = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [dataTable, setDataTable] = useState([]);
  const [deletedRows, setDeletedRows] = useState([]);
  const [addedRows, setAddedRows] = useState([]);

  const [selectedProiority, setSelectedProiority] = useState({});
  // const [allocationSumState, setAllocationSumState] = useState(0);

  const [anchorEl, setAnchorEl] = useState(null);

  const open = Boolean(anchorEl);
  const id = open ? "popoverr" : undefined;

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

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

  const { poultryRequestsTotalQuantity } = useSelector(
    (state) => state.citySlice
  );

  const { provinceGetAutoAllocations } = useSelector(
    (state) => state.provinceSlice
  );

  useEffect(() => {
    dispatch(provinceGetAutoAllocationsService());
  }, []);

  useEffect(() => {
    setDataTable(deepCopy(provinceGetAutoAllocations));
  }, [provinceGetAutoAllocations]);

  const sendEditTableService = () => {
    const combinedArr = dataTable?.reduce((acc, curr) => {
      let d = deepCopy(curr.allocations);
      d = d.filter((item) => item.allocationKey);
      return [...acc, ...d];
    }, []);
    dispatch(
      provinceDeleteAutoAllocationService({
        allocation_delete_list: deletedRows?.filter(
          (item) => item.allocationKey
        ),
      })
    ).then(() => {
      setDeletedRows([]);
      dispatch(
        provinceAddAutoAllocationService({
          allocation_add_list: addedRows,
        })
      ).then(() => {
        dispatch(
          provinceEditAutoAllocationService({
            allocation_list: combinedArr,
          })
        ).then((r) => {
          setAddedRows([]);
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            dispatch(getPoultryRequestsTotalQuantityService());
            dispatch(provinceGetAutoAllocationsService());
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
          }
        });
      });
    });
  };

  const checkForDebt = () => {
    // check if there are debt

    const mapedDebts = dataTable.map((element) => {
      const hasDebt = element.allocations.some((allocation) => allocation.debt);
      return hasDebt;
    });
    const res = mapedDebts.some((item) => item);
    return res;
  };

  const sendFinalTableService = () => {
    const combinedArr = dataTable?.reduce((acc, curr) => {
      let d = deepCopy(curr.allocations);
      d = d.filter((item) => item.allocationKey);
      return [...acc, ...d];
    }, []);
    dispatch(
      provinceDeleteAutoAllocationService({
        allocation_delete_list: deletedRows?.filter(
          (item) => item.allocationKey
        ),
      })
    ).then(() => {
      setDeletedRows([]);
      dispatch(
        provinceAddAutoAllocationService({
          allocation_add_list: addedRows,
        })
      ).then(() => {
        dispatch(
          provinceEditAutoAllocationService({
            allocation_list: combinedArr,
          })
        ).then(() => {
          setAddedRows([]);

          const allocationsForCancel = provinceGetAutoAllocations?.reduce(
            (total, item) => {
              return [...total, ...item.allocations];
            },
            []
          );
          const allocationsKeys = allocationsForCancel.map((item) => {
            return { allocationKey: item.allocationKey };
          });
          dispatch(
            provinceSubmitFinalAutoAllocationsService({
              final_registration_list: allocationsKeys,
            })
          ).then((r) => {
            if (r.payload.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: r.payload.error,
                severity: "error",
              });
            } else {
              dispatch(getPoultryRequestsTotalQuantityService());
              dispatch(provinceGetAutoAllocationsService());
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
              });
            }
          });
        });
      });
    });
  };

  const sumOfAllocationQuantity =
    Array.isArray(dataTable) &&
    dataTable?.reduce((total, item) => {
      return (
        total +
        item.allocations?.reduce((allocationTotal, allocation) => {
          return allocationTotal + allocation.allocationQuantity;
        }, 0)
      );
    }, 0);

  const sumAllocationsSum =
    Array.isArray(dataTable) &&
    dataTable?.reduce((total, item) => {
      return total + item.allocationsSum;
    }, 0);

  // const sumOfAllocationPercent = provinceGetAutoAllocations?.reduce(
  //   (total, item) => {
  //     return (
  //       total +
  //       item.allocations.reduce((allocationTotal, allocation) => {
  //         return allocationTotal + allocation.allocationPercent;
  //       }, 0)
  //     );
  //   },
  //   0
  // );

  const sumOfKillRequests =
    Array.isArray(dataTable) &&
    dataTable?.reduce((total, item) => {
      return total + item.poultryQuantity;
    }, 0);

  const [dateForAutoAlloction, setDateForAutoAllocation] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );

  useEffect(() => {
    dispatch(getPoultryRequestsTotalQuantityService(dateForAutoAlloction));
  }, [dateForAutoAlloction]);

  const handleList = (selected) => {
    const d = selected.map((item) => {
      return {
        [item.key]: item.value,
      };
    });
    setSelectedProiority(d);
  };

  return (
    <Grid
      container
      my={SPACING.SMALL}
      direction="column"
      alignItems="start"
      xs={12}
      pt={2}
      px={2}
    >
      <SimpleTable
        name={
          <Grid xs={12} mb={2}>
            <DatePicker
              label="تاریخ تخصیص"
              id="date"
              renderInput={(params) => (
                <TextField style={{ width: "180px" }} {...params} />
              )}
              value={dateForAutoAlloction}
              onChange={(e) => {
                setDateForAutoAllocation(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
        }
        columns={[
          "تعداد کل درخواست کشتار",
          "تخصیص داده شده",
          "قابل تخصیص",
          "تعداد خریداران آماده به تخصیص",
          "تعداد مرغدار",
        ]}
        data={[
          [
            `${poultryRequestsTotalQuantity?.acceptedQuantity?.toLocaleString()} قطعه`,
            `${poultryRequestsTotalQuantity?.allocatedQuantity?.toLocaleString()} قطعه`,
            `${poultryRequestsTotalQuantity?.assignableQuantity?.toLocaleString()} قطعه`,
            `${poultryRequestsTotalQuantity?.numberOfKillHouse?.toLocaleString()} واحد`,
            `${poultryRequestsTotalQuantity?.numberOfPoultry?.toLocaleString()} واحد`,
          ],
        ]}
      />

      <Grid
        container
        gap={SPACING.SMALL}
        my={SPACING.SMALL}
        justifyContent="center"
        alignItems="center"
        width="100%"
      >
        <Grid
          container
          alignItems="center"
          justifyContent="center"
          direction="column"
          gap={SPACING.SMALL}
          width="100%"
        >
          <Typography fontWeight="bold">اولویت بندی کشتارگاه</Typography>
          <ProvinceAutoSelectOptions handleList={handleList} />
          <Grid>
            <Button
              variant="contained"
              color="primary"
              disabled={dataTable.length}
              onClick={() => {
                dispatch(
                  provinceCreateAutoAllocationService({
                    date: dateForAutoAlloction,
                    filter_list: selectedProiority,
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    dispatch(getPoultryRequestsTotalQuantityService());
                    dispatch(provinceGetAutoAllocationsService());
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
              }}
            >
              ایجاد تخصیص خودکار
            </Button>
          </Grid>
        </Grid>
      </Grid>

      {!!dataTable?.length && (
        <>
          <Grid mb={SPACING.SMALL}>
            <Typography fontWeight="bold" color="error">
              * توجه: رنگ قرمز خریدار نشان دهنده بدهی قبلی است.
            </Typography>
          </Grid>

          <table className="auto-allocation-table">
            <tr>
              <th>ردیف</th>
              <th>واحد (مرغدار)</th>
              <th>تعداد درخواست کشتار</th>
              <th>وزن تقریبی درخواست کشتار</th>
              <th>مانده قابل تخصیص</th>
              <th>اضافه</th>
              <th>ماهیت خریدار</th>
              <th>خریدار</th>
              <th>محل کشتار</th>
              <th>تعداد تخصیص</th>
              <th>جمع مرغ تخصیصی</th>
              <th>سهم درصد</th>
              <th>حواله مرغدار</th>
              <th>حواله خریدار</th>
              <th>حذف</th>
            </tr>
            {dataTable?.map((poultryRequestItem, j) => {
              // const sumOfAllocation = poultryRequestItem.allocations?.reduce(
              //   (total, item) => {
              //     return total + item.allocationQuantity;
              //   },
              //   0
              // );
              return poultryRequestItem?.allocations?.map((slaughter, i) => {
                let reaminForAllocation =
                  poultryRequestItem?.poultryQuantity -
                  poultryRequestItem?.allocationsSum;

                // if (reaminForAllocation < 0) {
                //   reaminForAllocation = (
                //     <Typography color={"#f2f2f2"}>{reaminForAllocation}</Typography>
                //   );
                // }

                return (
                  <tr key={i}>
                    {!i && (
                      <td
                        rowSpan={poultryRequestItem?.allocations.length}
                        style={{
                          backgroundColor: j % 2 === 0 ? "#fff" : "#f2f2f2",
                        }}
                      >
                        {j + 1}
                      </td>
                    )}

                    {!i && (
                      <td
                        rowSpan={poultryRequestItem?.allocations.length}
                        style={{
                          backgroundColor: j % 2 === 0 ? "#fff" : "#f2f2f2",
                        }}
                      >
                        {poultryRequestItem?.poultryName} (
                        {poultryRequestItem?.poultryAddress}) (
                        {poultryRequestItem?.poultryMobile})
                      </td>
                    )}

                    {!i && (
                      <td
                        rowSpan={poultryRequestItem?.allocations.length}
                        style={{
                          backgroundColor: j % 2 === 0 ? "#fff" : "#f2f2f2",
                        }}
                      >
                        {poultryRequestItem?.poultryQuantity?.toLocaleString()}
                      </td>
                    )}

                    {!i && (
                      <td
                        rowSpan={poultryRequestItem?.allocations.length}
                        style={{
                          backgroundColor: j % 2 === 0 ? "#fff" : "#f2f2f2",
                        }}
                      >
                        وزن تقریبی:{" "}
                        {poultryRequestItem?.poultryRequestWeight?.toLocaleString()}
                        <hr />
                        میانگین وزن:{" "}
                        {poultryRequestItem?.poultryRequestIndexWeight}
                      </td>
                    )}

                    {!i && (
                      <td
                        rowSpan={poultryRequestItem?.allocations.length}
                        style={{
                          backgroundColor: j % 2 === 0 ? "#fff" : "#f2f2f2",
                        }}
                      >
                        {/* {poultryRequestItem?.poultryRemainQuantity} */}
                        {reaminForAllocation.toLocaleString()}
                      </td>
                    )}
                    {!i && (
                      <td
                        rowSpan={poultryRequestItem?.allocations.length}
                        style={{
                          backgroundColor: j % 2 === 0 ? "#fff" : "#f2f2f2",
                        }}
                      >
                        <IconButton
                          color="primary"
                          onClick={() => {
                            dispatch(
                              OPEN_MODAL({
                                title: "اضافه کردن خریدار",
                                content: (
                                  <ProvinceAddBuyerAutoAllocation
                                    dataTable={dataTable}
                                    poultryIndex={j}
                                    setDataTable={setDataTable}
                                    setAddedRows={setAddedRows}
                                  />
                                ),
                              })
                            );
                            // setDataTable((prevState) => {
                            //   // let edited = Array.from(prevState);
                            //   let edited = deepCopy(prevState);

                            //   edited[j].allocationsSum = edited[
                            //     j
                            //   ].allocations?.reduce((total, item) => {
                            //     return total + item.allocationQuantity;
                            //   }, 0);

                            //   return edited;
                            // });
                          }}
                        >
                          <AddIcon />
                        </IconButton>
                      </td>
                    )}

                    <td
                      style={{
                        backgroundColor: j % 2 === 0 ? "#fff" : "#f2f2f2",
                        color: slaughter.debt ? "red" : "",
                      }}
                    >
                      {slaughter?.type ? "کشتارکن" : "کشتارگاه"}{" "}
                      {slaughter.debt ? "(بدهکار)" : ""}
                    </td>

                    <td
                      style={{
                        backgroundColor: j % 2 === 0 ? "#fff" : "#f2f2f2",
                        color: slaughter.debt ? "red" : "",
                      }}
                    >
                      {slaughter?.buyerName} ({slaughter?.buyerAddress}) (
                      {slaughter?.buyerMobile})
                    </td>
                    <td
                      style={{
                        backgroundColor: j % 2 === 0 ? "#fff" : "#f2f2f2",
                        color: slaughter.debt ? "red" : "",
                      }}
                    >
                      {slaughter?.KillingPlace}
                    </td>

                    <td
                      style={{
                        backgroundColor: j % 2 === 0 ? "#fff" : "#f2f2f2",
                      }}
                    >
                      <TextField
                        style={{
                          width: "100px",
                        }}
                        type={"number"}
                        color={slaughter.debt ? "error" : ""}
                        inputProps={{
                          style: {
                            color: slaughter.debt ? "red" : "", // Set your desired color here
                          },
                        }}
                        value={slaughter?.allocationQuantity}
                        onChange={(e) => {
                          if (Number(e.target.value) < 1) {
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: "در صورت نیاز به کاهش کمتر از 1 از گزینه حذف استفاده نمایید.",
                              severity: "error",
                            });
                            return;
                          }
                          setDataTable((prevState) => {
                            // let edited = Array.from(prevState);
                            let edited = deepCopy(prevState);
                            edited[j].allocations[i].allocationQuantity =
                              Number(e.target.value);

                            edited[j].allocationsSum = edited[
                              j
                            ].allocations?.reduce((total, item) => {
                              return total + item.allocationQuantity;
                            }, 0);

                            return edited;
                          });
                        }}
                      />
                    </td>
                    {!i && (
                      <td
                        rowSpan={poultryRequestItem?.allocations.length}
                        style={{
                          backgroundColor: j % 2 === 0 ? "#fff" : "#f2f2f2",
                          color: slaughter.debt ? "red" : "",
                        }}
                      >
                        {poultryRequestItem?.allocationsSum?.toLocaleString()}
                        {/* {sumOfAllocation} */}
                      </td>
                    )}
                    <td
                      style={{
                        backgroundColor: j % 2 === 0 ? "#fff" : "#f2f2f2",
                        color: slaughter.debt ? "red" : "",
                      }}
                    >
                      %
                      {(
                        (slaughter?.allocationQuantity /
                          sumOfAllocationQuantity) *
                        100
                      ).toFixed(2)}
                    </td>
                    {!i && (
                      <td
                        rowSpan={poultryRequestItem?.allocations.length}
                        style={{
                          backgroundColor: j % 2 === 0 ? "#fff" : "#f2f2f2",
                        }}
                      >
                        <IconButton disabled={true} color="primary">
                          <a
                            href={`https://core-inventory.iran.liara.run/pdf/aviculture-remittance?poultryRequestKey=${poultryRequestItem.poultryRequestKey}&which=${window.location.origin}`}
                          >
                            <PrintIcon />
                          </a>
                        </IconButton>
                      </td>
                    )}
                    <td
                      style={{
                        backgroundColor: j % 2 === 0 ? "#fff" : "#f2f2f2",
                      }}
                    >
                      <IconButton disabled={true} color="primary">
                        <a
                          href={`https://core-inventory.iran.liara.run/pdf/buyer-remittance?allocationKey=${slaughter.allocationKey}&which=${window.location.origin}`}
                        >
                          <PrintIcon />
                        </a>
                      </IconButton>
                    </td>
                    <td
                      style={{
                        backgroundColor: j % 2 === 0 ? "#fff" : "#f2f2f2",
                      }}
                    >
                      <IconButton
                        color="error"
                        onClick={() => {
                          setDataTable((prevState) => {
                            // let edited = Array.from(prevState);
                            let edited = deepCopy(prevState);
                            setDeletedRows([
                              ...deletedRows,
                              edited[j].allocations[i],
                            ]);
                            edited[j].allocations.splice(i, 1);

                            edited[j].allocationsSum = edited[
                              j
                            ].allocations?.reduce((total, item) => {
                              return total + item.allocationQuantity;
                            }, 0);
                            return edited;
                          });
                        }}
                      >
                        <DeleteIcon />
                      </IconButton>
                    </td>
                  </tr>
                );
              });
            })}
            <tr>
              <td colSpan={"10"}>جمع کل</td>
              <td>{sumOfAllocationQuantity.toLocaleString()}</td>
              <td>{sumAllocationsSum.toLocaleString()}</td>
              <td>
                {/* {sumOfAllocationPercent} */}%
                {((sumOfAllocationQuantity / sumOfKillRequests) * 100).toFixed(
                  2
                )}
              </td>
              <td colSpan={3}>
                <Button
                  aria-describedby={id}
                  variant="contained"
                  color="primary"
                  onClick={handleClick}
                  fullWidth
                >
                  عملیات
                </Button>
                <Popover
                  anchorOrigin={{
                    vertical: "bottom",
                    horizontal: "right",
                  }}
                  transformOrigin={{
                    vertical: "top",
                    horizontal: "left",
                  }}
                  id={id}
                  open={open}
                  anchorEl={anchorEl}
                  onClose={handleClose}
                >
                  <div style={{ padding: "20px" }}>
                    <Grid container direction="column" gap={SPACING.TINY}>
                      <Button
                        variant="contained"
                        color="success"
                        onClick={() => {
                          sendEditTableService();
                        }}
                      >
                        ثبت موقت
                      </Button>
                      <Button
                        variant="contained"
                        color="error"
                        onClick={() => {
                          const allocationsForCancel =
                            provinceGetAutoAllocations?.reduce(
                              (total, item) => {
                                return [...total, ...item.allocations];
                              },
                              []
                            );
                          const allocationsKeys = allocationsForCancel.map(
                            (item) => {
                              return { allocationKey: item.allocationKey };
                            }
                          );
                          dispatch(
                            provinceSubmitFinalAutoAllocationsService({
                              cancellation: allocationsKeys,
                            })
                          ).then((r) => {
                            if (r.payload.error) {
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: r.payload.error,
                                severity: "error",
                              });
                            } else {
                              dispatch(
                                getPoultryRequestsTotalQuantityService()
                              );
                              dispatch(provinceGetAutoAllocationsService());
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: "عملیات با موفقیت انجام شد.",
                                severity: "success",
                              });
                            }
                          });
                        }}
                      >
                        لغو تخصیص خودکار
                      </Button>
                      <Button
                        variant="contained"
                        onClick={() => {
                          if (checkForDebt()) {
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: "عدم بدهی در اولویت تخصیص خودکار شما می باشد. لطفا تخصیص را مدیریت نمایید.",
                              severity: "error",
                            });
                            handleClose();
                          } else {
                            sendFinalTableService();
                            handleClose();
                          }
                        }}
                      >
                        ثبت نهایی
                      </Button>
                    </Grid>
                  </div>
                </Popover>
              </td>
            </tr>
          </table>
        </>
      )}

      {!dataTable.length && (
        <Grid container>
          <Typography>تخصیص خودکار ایجاد نشده است!</Typography>
        </Grid>
      )}
    </Grid>
  );
};

function deepCopy(obj) {
  let newObj = Array.isArray(obj) ? [] : {};
  for (let key in obj) {
    if (typeof obj[key] === "object" && obj[key] !== null) {
      newObj[key] = deepCopy(obj[key]);
    } else {
      newObj[key] = obj[key];
    }
  }
  return newObj;
}
