import { useDispatch, useSelector } from "react-redux";
import { useContext, useEffect, useState } from "react";
import { getProvinceBuyerStewardAllocationService } from "../../services/get-province-buyer-steward-allocation";
import { useParams } from "react-router-dom";
import { AdvancedTable } from "../../../../components/advanced-table/AdvancedTable";
import { Button, TextField, Tooltip, Typography } from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { SPACING } from "../../../../data/spacing";
import { provinceBuyerRealCarcassesService } from "../../services/province-buyer-real-carcasses";
import { AppContext } from "../../../../contexts/AppContext";
import { provinceAutomaticStewardAllocationService } from "../../services/province-automatic-steward-allocation";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { provinceUpdateAllocateStewardsService } from "../../services/province-update-allocate-stewards";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { RiFileExcel2Fill } from "react-icons/ri";
import axios from "axios";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { slaughterGetUpdatedInventoryStock } from "../../../slaughter-house/services/salughter-get-updated-inventory-stock";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment/moment";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { formatJustDate } from "../../../../utils/formatTime";
import { ProvinceManageStewardAllocations } from "../province-manage-steward-allocations/ProvinceManageStewardAllocations";
import { provinceGetTotalReportAgentShareService } from "../../services/province-get-total-report-agent-share";

export const ProvinceBuyerStewardAllocation = () => {
  const dispatch = useDispatch();
  let currentDate = moment(new Date()).format("YYYY-MM-DD");
  const { id, date } = useParams();
  const [datePicker, setDatePicker] = useState(
    moment(new Date()).format("YYYY-MM-DD")
  );

  if (getRoleFromUrl() === "KillHouse") {
    currentDate = datePicker;
  } else {
    currentDate = date;
  }

  const [dataTable, setDataTable] = useState([]);
  const {
    getProvinceBuyerStewardAllocation,
    provinceGetTotalReportAgentShare,
  } = useSelector((state) => state.provinceSlice);

  const { slaughterUpdatedInventoryStock } = useSelector(
    (state) => state.slaughterSlice
  );

  const updateInventory = () => {
    dispatch(
      slaughterGetUpdatedInventoryStock({
        date: currentDate,
        kill_house_key: id,
      })
    );
  };

  useEffect(() => {
    dispatch(
      provinceGetTotalReportAgentShareService({
        date: currentDate,
        kill_house_key: id,
      })
    );
    if (getRoleFromUrl() === "KillHouse") {
      dispatch(
        provinceUpdateAllocateStewardsService({
          kill_house_key: id,
          date: currentDate,
        })
      ).then(() => {
        dispatch(
          getProvinceBuyerStewardAllocationService({
            date: currentDate,
            killHouseKey: id,
          })
        ).then(() => {
          dispatch(
            slaughterGetUpdatedInventoryStock({
              date: currentDate,
              kill_house_key: id,
            })
          );
        });
      });
    }

    if (getRoleFromUrl() === "ProvinceOperator") {
      dispatch(
        getProvinceBuyerStewardAllocationService({
          date: currentDate,
          killHouseKey: id,
        })
      ).then(() => {
        dispatch(
          slaughterGetUpdatedInventoryStock({
            date: currentDate,
            kill_house_key: id,
          })
        );
      });
    }
  }, [currentDate]);

  const updateTable = () => {
    dispatch(
      getProvinceBuyerStewardAllocationService({
        date: currentDate,
        killHouseKey: id,
      })
    );
  };

  useEffect(() => {
    const d = getProvinceBuyerStewardAllocation?.map((item) => {
      return [
        item.steward.guilds.guildsId,
        // formatJustDate(item.steward.guilds.createDate),
        item.steward.guilds.steward ? "مباشر" : "صنف",
        item.steward.guilds.guildsName,
        item.steward.guilds.user.fullname,
        // item.steward?.guilds?.user?.nationalId,
        item.steward?.guilds?.user?.mobile,
        `${item.steward?.guilds?.typeActivity}/${item.steward?.guilds?.areaActivity}`,
        item.steward?.guilds?.licenseNumber,
        item.steward?.guilds?.address.city.name,
        <Grid container key={item.key} direction="column">
          <Grid>{`${item?.numberOfCarcasses?.toLocaleString()} قطعه`}</Grid>
          <Grid>{`${item?.weightOfCarcasses?.toLocaleString()} کیلوگرم`}</Grid>
        </Grid>,
        <Grid container key={item.key} direction="column">
          {item.state === "accepted" && (
            <>
              <Grid>{`${item?.realNumberOfCarcasses?.toLocaleString()} قطعه`}</Grid>
              <Grid>{`${item?.realWeightOfCarcasses?.toLocaleString()} کیلوگرم`}</Grid>
            </>
          )}

          {!item.systemRegistrationCode && (
            <Grid>
              <Button
                onClick={() => {
                  dispatch(
                    OPEN_MODAL({
                      title: "ویرایش تعداد / وزن لاشه",
                      content: (
                        <RealCarcassesInput
                          key={item.key}
                          realWeightOfCarcasses={item.realWeightOfCarcasses}
                          realNumberOfCarcasses={item.realNumberOfCarcasses}
                          item={item}
                          updateTable={updateTable}
                        />
                      ),
                    })
                  );
                }}
              >
                {item.state === "accepted" ? "ویرایش" : "وارد کردن اطلاعات"}
              </Button>
            </Grid>
          )}
        </Grid>,
        // <RealCarcassesInput
        //   key={item.key}
        //   realWeightOfCarcasses={item.realWeightOfCarcasses}
        //   realNumberOfCarcasses={item.realNumberOfCarcasses}
        //   item={item}
        //   updateTable={updateTable}
        // />,
        <RegistrationInput
          key={item.key}
          loggedRegistrationCode={item.loggedRegistrationCode}
          item={item}
          updateTable={updateTable}
          updateInventory={updateInventory}
        />,
      ];
    });

    setDataTable(d);
  }, [getProvinceBuyerStewardAllocation]);

  const [inventoryDate, setInventoryDate] = useState(new Date(currentDate));

  useEffect(() => {
    const tempDate = new Date(inventoryDate);
    tempDate.setDate(new Date(currentDate).getDate() - 1);
    setInventoryDate(tempDate);
  }, [currentDate]);

  return (
    <Grid
      container
      alignItems="center"
      justifyContent="start"
      gap={SPACING.SMALL}
    >
      <Grid
        container
        alignItems="center"
        justifyContent="start"
        gap={SPACING.SMALL}
      >
        {/* <Typography>سهم بندی ها</Typography> */}
        {getRoleFromUrl() === "KillHouse" && (
          <DatePicker
            label="تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "150px" }} {...params} />
            )}
            value={currentDate}
            onChange={(e) => {
              setDatePicker(moment(e).format("YYYY-MM-DD"));
            }}
          />
        )}
      </Grid>
      <Grid width="100%">
        <SimpleTable
          name={
            <Grid container alignItems="center">
              <Typography>
                سهم بندی برای تاریخ کشتار مورخ {formatJustDate(inventoryDate)}{" "}
                {provinceGetTotalReportAgentShare?.killer
                  ? "کشتارکن"
                  : "کشتارگاه"}{" "}
                {provinceGetTotalReportAgentShare?.name}
              </Typography>

              <Tooltip title="خروجی اکسل">
                <a
                  href={`${axios.defaults.baseURL}Broadcast_management/?date=${date}&kill_house_key=${id}`}
                  rel="noreferrer"
                >
                  <Button color="success">
                    <RiFileExcel2Fill size={32} />
                  </Button>
                </a>
              </Tooltip>
            </Grid>
          }
          columns={[
            "حجم لاشه ها",
            "وزن لاشه ها (کیلوگرم)",
            "حجم لاشه تخصیص داده شده",
            "وزن تخصیص داده شده (کیلوگرم)",
            "حجم لاشه قابل تخصیص",
            "وزن قابل تخصیص (کیلوگرم)",
          ]}
          data={[
            [
              slaughterUpdatedInventoryStock?.totalNumberOfCarcasses?.toLocaleString(),
              slaughterUpdatedInventoryStock?.totalWeightOfCarcasses?.toLocaleString(),
              slaughterUpdatedInventoryStock?.allocatedTotalNumberOfCarcasses?.toLocaleString(),
              slaughterUpdatedInventoryStock?.allocatedTotalWeightOfCarcasses?.toLocaleString(),
              slaughterUpdatedInventoryStock?.remainTotalNumberOfCarcasses?.toLocaleString(),
              slaughterUpdatedInventoryStock?.remainTotalWeightOfCarcasses?.toLocaleString(),
            ],
          ]}
        />
      </Grid>

      {(getRoleFromUrl() === "ProvinceOperator" ||
        getRoleFromUrl() === "SuperAdmin") && (
        <ProvinceManageStewardAllocations />
      )}

      {getRoleFromUrl() === "KillHouse" && (
        <AdvancedTable
          name={
            <Grid container alignItems="center" gap={SPACING.SMALL}>
              {/* <Typography>سهم بندی اتوماتیک</Typography>
            {getRoleFromUrl() === "KillHouse" && (
              <DatePicker
                label="تاریخ"
                id="date"
                renderInput={(params) => (
                  <TextField style={{ width: "150px" }} {...params} />
                )}
                value={date}
                onChange={(e) => {
                  setDatePicker(moment(e).format("YYYY-MM-DD"));
                }}
              />
            )} */}

              {/* <Button
              variant="contained"
              disabled={
                getProvinceBuyerStewardAllocation?.length
                  ? getProvinceBuyerStewardAllocation?.some(
                      (item) => item.state === "accepted"
                    )
                  : true
              }
              onClick={() => {
                dispatch(
                  provinceAutomaticStewardAllocationService({
                    send_registration_code: true,
                    steward_allocation_list:
                      getProvinceBuyerStewardAllocation?.map(
                        (item) => item.key
                      ),
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    updateTable();
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
              }}
            >
              ثبت و ارسال کداحراز
            </Button> */}
            </Grid>
          }
          columns={[
            "شناسه صنف",
            // "تاریخ ثبت",
            "ماهیت",
            "نام واحد صنفی",
            "نام شخص/شرکت",
            // "کدملی",
            "موبایل",
            "نوع/حوزه فعالیت",
            "شماره مجوز",
            "شهرستان",
            "تعداد/وزن لاشه پیشنهادی",
            "تعداد/وزن لاشه تحویلی",
            "کداحراز",
          ]}
          data={dataTable}
        />
      )}
    </Grid>
  );
};

const validationSchema = Yup.object({
  number1: Yup.number().required("این فیلد اجباری است"),
  number2: Yup.number().required("این فیلد اجباری است"),
});
const RealCarcassesInput = ({
  // realWeightOfCarcasses,
  // realNumberOfCarcasses,
  updateTable,
  item,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const formik = useFormik({
    initialValues: {
      number1: item.realNumberOfCarcasses,
      number2: item.realWeightOfCarcasses,
    },
    validationSchema: validationSchema,
  });
  // const [numberInput, setNumberInput] = useState(realNumberOfCarcasses);
  // const [textInput, setTextInput] = useState(realWeightOfCarcasses);

  // const handleNumberInputChange = (e) => {
  //   setNumberInput(e.target.value);
  // };

  // const handleTextInputChange = (e) => {
  //   setTextInput(e.target.value);
  // };

  useEffect(() => {
    formik.validateForm();
  }, []);

  return (
    <Grid
      container
      direction="column"
      width="100%"
      // flexWrap="nowrap"
      gap={SPACING.SMALL}
    >
      <NumberInput
        // value={textInput}
        label="وزن (کیلوگرم)"
        id="number2"
        // size="small"
        allowLeadingZeros
        thousandSeparator=","
        // onChange={handleTextInputChange}
        // style={{ width: "85px" }}
        // disabled={item.state === "accepted"}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        value={formik.values.number2}
        error={formik.touched.number2 && Boolean(formik.errors.number2)}
        helperText={formik.touched.number2 && formik.errors.number2}
      />
      <NumberInput
        label="تعداد"
        // value={numberInput}
        id="number1"
        // size="small"
        // onChange={handleNumberInputChange}
        allowLeadingZeros
        thousandSeparator=","
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        value={formik.values.number1}
        error={formik.touched.number1 && Boolean(formik.errors.number1)}
        helperText={formik.touched.number1 && formik.errors.number1}
        // style={{ width: "75px" }}
        // disabled={item.state === "accepted"}
      />
      {/* {item.state !== "accepted" && ( */}
      <Button
        variant="contained"
        disabled={!formik.isValid}
        onClick={() => {
          dispatch(
            provinceBuyerRealCarcassesService({
              confirm_information: true,
              steward_allocation_key: item.key,
              real_number_of_carcasses: Number(formik.values.number1),
              real_weight_of_carcasses: Number(formik.values.number2),
            })
          ).then((r) => {
            dispatch(CLOSE_MODAL());
            if (r.payload.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: r.payload.error,
                severity: "error",
              });
            } else {
              updateTable();
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
              });
            }
          });
        }}
      >
        ثبت
      </Button>
      {/* )} */}
    </Grid>
  );
};

const RegistrationInput = ({
  loggedRegistrationCode,
  item,
  updateTable,
  updateInventory,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [textInput, setTextInput] = useState(loggedRegistrationCode);

  const handleTextInputChange = (e) => {
    setTextInput(e.target.value);
  };

  return (
    <Grid
      container
      width="100%"
      flexWrap="nowrap"
      alignItems="center"
      justifyContent="center"
    >
      {item.systemRegistrationCode ? (
        <Grid>
          <TextField
            value={textInput}
            size="small"
            onChange={handleTextInputChange}
            style={{ width: "85px" }}
            disabled={item?.finalRegistration}
          />
          {!item?.finalRegistration && (
            <Button
              size="small"
              onClick={() => {
                dispatch(
                  provinceBuyerRealCarcassesService({
                    enter_registration_code: true,
                    steward_allocation_key: item.key,
                    logged_registration_code: textInput,
                    role: getRoleFromUrl(),
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    updateTable();
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
              }}
            >
              ثبت
            </Button>
          )}
        </Grid>
      ) : (
        <Button
          disabled={item.state !== "accepted"}
          onClick={() => {
            dispatch(
              OPEN_MODAL({
                title: "ارسال کداحراز",
                content: (
                  <Grid container gap={SPACING.SMALL}>
                    <Typography>
                      در صورت ارسال کداحراز انجام هیچگونه عملیاتی مانند حذف و
                      ویرایش امکان پذیر نمی باشد.
                    </Typography>
                    <Grid
                      container
                      direction="column"
                      gap={SPACING.TINY}
                      width="100%"
                    >
                      <Button
                        fullWidth
                        variant="contained"
                        onClick={() => {
                          dispatch(
                            provinceAutomaticStewardAllocationService({
                              send_registration_code: true,
                              steward_allocation_list: [item.key],
                            })
                          ).then((r) => {
                            if (r.payload.error) {
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: r.payload.error,
                                severity: "error",
                              });
                            } else {
                              dispatch(CLOSE_MODAL());
                              updateTable();
                              updateInventory();
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: "عملیات با موفقیت انجام شد.",
                                severity: "success",
                              });
                            }
                          });
                        }}
                      >
                        تایید
                      </Button>
                      <Button
                        fullWidth
                        color="error"
                        variant="contained"
                        onClick={() => {
                          dispatch(CLOSE_MODAL());
                        }}
                      >
                        لغو
                      </Button>
                    </Grid>
                  </Grid>
                ),
              })
            );
          }}
        >
          ارسال کداحراز
        </Button>
      )}
    </Grid>
  );
};
