import {
  TimelineConnector,
  TimelineContent,
  TimelineDot,
  TimelineOppositeContent,
  TimelineSeparator,
} from "@mui/lab";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  TextField,
  // FormControl,
  // FormControlLabel,
  // Radio,
  // RadioGroup,
  Typography,
} from "@mui/material";
import React, { useEffect, useState } from "react";
import { PropTypes } from "prop-types";
import TimelineItem from "@mui/lab/TimelineItem";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import useGetAllocationInformation from "../../hooks/useGetAllocationInformation";
import { SPACING } from "../../../../data/spacing";
import { useDispatch, useSelector } from "react-redux";
// import PendingIcon from "@mui/icons-material/Pending";
import AccessTimeIcon from "@mui/icons-material/AccessTime";
import { format } from "date-fns-jalali";
// import { getSlaughterHousesRequest } from "../../services/getSlaughterHousesRequest";
import { ProvinceAuction } from "../province-auction/ProvinceAuction";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import ThumbDownAltIcon from "@mui/icons-material/ThumbDownAlt";
import { avicultureGetChickenPrice } from "../../../aviculture/services/aviculture-get-chicken-price";
import { provinceRemoveAllocation } from "../../services/province-remove-allocation";
import { SlaghterHouseRequestAllocationItem } from "../slaghterhouse-request-allocation-Item/SlaghterHouseRequestAllocationItem";
import { poultryRequestIndexWeightService } from "../../services/city-edit-avculture.info";
import MyTable from "../../../../components/my-table/MyTable";
import { getAllocationInformation } from "../../services/get-allocation-information";
import { provinceGetAllRequests } from "../../../province/services/province-get-all-requests";
import { getSlaughterHousesRequest } from "../../services/getSlaughterHousesRequest";
import useRequestFile, { getFileFromApi } from "../../hooks/useRequestFile";
import useUserProfile from "../../../authentication/hooks/useUserProfile";
import { LOADING_END, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
// import useRequestFile from "../../hooks/useRequestFile";
import { ProvinceEditPoultryRequestForm } from "../../../province/components/province-edit-poultry-request-form/ProvinceEditPoultryRequestForm";
import { ProvinceAllocated } from "../province-allocated/ProvinceAllocated";

export const ProvinceAllocation = ({
  id,
  orginalQuantity,
  // file,
  item,
  // remainQuantity,
  getItemFreeSaleInProvince,
  updateTable,
}) => {
  const myFile = useRequestFile(id);
  const file = myFile?.file?.process;
  const [openNotif, , selectedDate1] = useContext(AppContext);
  const remainQuantity = file?.poultry?.poultryRemainQuantity;
  let { slaughterHousesRequest } = useSelector((state) => state.fileSlice);
  const [, setRequestedWeight] = useState();
  const [, setRequestedBuyType] = useState();

  const [fileQauntity, setFileQauntity] = useState(remainQuantity);

  useEffect(() => {
    setFileQauntity(remainQuantity);
  }, [remainQuantity, file]);

  const [allEntredQauntity, setAllEntredQauntity] = useState(null);

  const handleAllEntredQauntity = (q) => {
    setAllEntredQauntity(q);
  };

  useEffect(() => {
    // if (allEntredQauntity === null) {
    // let obj = {};
    // slaughterHousesRequest.map((item, i) => {
    //   obj = { ...obj, [i]: item.remainQuantity };
    // });
    // setAllEntredQauntity(obj);
    // } else {
    // const getSum = (a, b) => a + b;
    // const dd = Object.values(allEntredQauntity).reduce(getSum, 0);
    // setFileQauntity(file.poultry.poultryQuantity - dd);
    // }
    if (allEntredQauntity !== null) {
      const getSum = (a, b) => a + b;
      const dd = Object.values(allEntredQauntity).reduce(getSum, 0);
      setFileQauntity(remainQuantity - dd);
    }
  }, [allEntredQauntity]);

  useEffect(() => {
    dispatch(poultryRequestIndexWeightService());
    dispatch(getSlaughterHousesRequest(file?.poultry?.poultryRequestKey));
  }, [file]);
  // const [allocateOrAuction, setAllocateOrAuction] = useState("allocate");
  const [allocateOrAuction] = useState("allocate");

  const [slaughterAllocationLimit] = useState();

  const getSum = (a, b) => a + b;
  const avgLast4KillhousesWeight = Array.isArray(slaughterHousesRequest)
    ? slaughterHousesRequest
        ?.map((item) => item.firstAverageWeight)
        ?.reduce(getSum, 0) / slaughterHousesRequest?.length
    : "";

  // useEffect(() => {
  //   dispatch(
  //     getSlaughterHousesRequest({ key: file.poultry.poultryRequestKey })
  //   );
  // }, []);

  const allocationInformation = useGetAllocationInformation(
    file?.poultry?.poultryRequestKey
  );

  const dispatch = useDispatch();
  const [roles] = useUserProfile();

  // const { avicultureChickenPrice } = useSelector(
  //   (state) => state.avicultureSlice
  // );

  // const liveChickenPrice = avicultureChickenPrice?.liveChickenPrice;

  // calc suggest price
  // const chickenWeight = parseFloat(
  //   file.poultry.poultryIndexWeight.split(" ")[0]
  // );
  // let suggestPrice = liveChickenPrice;
  // const standardChicken = 2.75;
  // const checkStep = 0.05;
  // const costPerStep = 500;

  // if (chickenWeight < 2.7) {
  //   const howMuchToReduce =
  //     ((standardChicken - chickenWeight).toFixed(2) / checkStep) * costPerStep;
  //   suggestPrice = liveChickenPrice - howMuchToReduce;
  // }

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

  const formik = useFormik({
    initialValues: {
      quantity: "",
      slaughterHouse: "",
      paymentType: "cash",
      // fee: "",
    },
    validationSchema: Yup.object({
      quantity: Yup.number()
        .test(
          "testlimit",
          "تعداد باید کمتر یا مساوی ظرفیت کشتارگاه و مانده درخواست باشد",
          (val, context) => {
            return (
              context.originalValue &&
              context.originalValue <= allocationInformation.quantity &&
              context.originalValue <= slaughterAllocationLimit &&
              context.originalValue > 0
            );
          }
        )
        // .max(allocationInformation.quantity, "بالاتر از ظرفیت وارد شده است")
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
      slaughterHouse: Yup.string().required("این فیلد اجباری است!"),
      paymentType: Yup.string().required("این فیلد اجباری است!"),
      // fee: Yup.number().required("این فیلد اجباری است!"),
    }),
  });

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

  useEffect(() => {
    if (!formik.values.slaughterHouse) {
      setRequestedBuyType(null);
      setRequestedWeight(null);
    }
  }, [formik.values.slaughterHouse]);

  const fileWeight = file?.poultry?.IndexWeight;
  let weightType;

  const { poultryRequestIndexWeight } = useSelector((state) => state.fileSlice);
  const avgPoultryRequestsWeight = poultryRequestIndexWeight?.ave;

  if (fileWeight > avgPoultryRequestsWeight) {
    weightType = "high";
  } else if (fileWeight < avgPoultryRequestsWeight) {
    weightType = "low";
  }

  slaughterHousesRequest = Array.isArray(slaughterHousesRequest)
    ? slaughterHousesRequest
    : [];
  const sortedSlaughterReqs = [...slaughterHousesRequest]?.sort(function (
    a,
    b
  ) {
    if (weightType === "high") {
      if (
        a.firstAverageWeight < b.firstAverageWeight &&
        a.killHouse.systemAddress?.city?.name === file?.poultry?.poultryCity
      ) {
        return -1;
        // return a.firstAverageWeight - b.firstAverageWeight;
      }
    }
    if (weightType === "low") {
      if (
        a.firstAverageWeight > b.firstAverageWeight &&
        a.killHouse.systemAddress?.city?.name === file?.poultry?.poultryCity
      ) {
        return -1;
        // return b.firstAverageWeight - a.firstAverageWeight;
      }
    }
    return 0;
  });

  const totalAllocatedMainQuantity = allocationInformation?.provinceAssignments
    ?.length
    ? allocationInformation?.provinceAssignments?.reduce(
        (accumulator, currentValue) => {
          if (currentValue.provinceKillRequestState !== "rejected") {
            return accumulator + currentValue.mainQuantity;
          }
          return accumulator;
        },
        0
      )
    : 0;
  const defaultValueForAllocate = orginalQuantity - totalAllocatedMainQuantity;

  const [searchText, setSearchText] = useState("");

  return (
    <TimelineItem sx={{ alignSelf: "flex-start", width: "100%" }}>
      <TimelineSeparator>
        <TimelineDot color="secondary" />
        <TimelineConnector />
      </TimelineSeparator>
      <Grid container direction="column" flexWrap="nowrap" flex="1">
        <Grid container>
          <Grid>
            <TimelineOppositeContent
              variant="body1"
              fontWeight="bold"
              color="secondary"
            >
              انجام عملیات
            </TimelineOppositeContent>
          </Grid>
          <Grid>
            <TimelineContent color="textSecondary">
              {/* <Typography variant="body2">
                در این مرحله سفارش را به کشتارگاه تخصیص دهید.
              </Typography> */}
              <Grid container gap={SPACING.LARGE} alignItems="center">
                <Typography
                  variant="body1"
                  color={fileQauntity < 0 ? "red" : "black"}
                >
                  تعداد اولیه درخواست کشتار: {orginalQuantity?.toLocaleString()}{" "}
                  قطعه
                  <Button
                    aria-label="delete"
                    color="primary"
                    onClick={() => {
                      dispatch(
                        OPEN_MODAL({
                          title: "ویرایش تعداد اولیه درخواست کشتار",
                          content: (
                            <ProvinceEditPoultryRequestForm
                              quantity={totalAllocatedMainQuantity}
                              poultryRequestKey={item.poultryRequest.key}
                            />
                          ),
                        })
                      );
                    }}
                  >
                    ویرایش
                  </Button>
                </Typography>
                <Typography
                  variant="body1"
                  color={fileQauntity < 0 ? "red" : "black"}
                >
                  تخصیص داده شده: ‌
                  {totalAllocatedMainQuantity?.toLocaleString()} قطعه
                  <Button
                    onClick={() => {
                      dispatch(
                        OPEN_MODAL({
                          title: "تخصیصات انجام شده",
                          content: (
                            <ProvinceAllocated
                              allocated={
                                allocationInformation?.provinceAssignments
                              }
                            />
                          ),
                        })
                      );
                    }}
                  >
                    مشاهده
                  </Button>
                </Typography>
                <Typography variant="body1" color={"green"}>
                  تعداد قابل تخصیص:‌ {fileQauntity?.toLocaleString()} قطعه
                </Typography>

                <Typography variant="body1" color={"primary"}>
                  مرغدار:‌{" "}
                  {`${item?.poultryRequest?.poultry?.unitName} (${item?.poultryRequest?.poultry?.userprofile?.mobile})`}
                </Typography>

                <Typography variant="body1" color={"primary"}>
                  نوع فروش:‌ {getItemFreeSaleInProvince(item)}
                </Typography>
              </Grid>
            </TimelineContent>
          </Grid>
        </Grid>
        {/* <Grid container>
          <FormControl
            sx={{
              flexDirection: "row",
            }}
          >
            <Grid container alignItems="center" gap={SPACING.MEDIUM}>
              <FormLabel>فروش از طریق</FormLabel>
              <RadioGroup
                row
                aria-labelledby="demo-row-radio-buttons-group-label"
                name="row-radio-buttons-group"
                onChange={(e) => {
                  setAllocateOrAuction(e.currentTarget.value);
                }}
              >
                <FormControlLabel
                  value="allocate"
                  control={<Radio />}
                  label="تخصیص به کشتارگاه"
                />
                <FormControlLabel
                  value="auction"
                  control={<Radio />}
                  label="مزایده"
                />
              </RadioGroup>
            </Grid>
          </FormControl>
        </Grid> */}

        {allocateOrAuction === "allocate" && (
          <Grid container direction="column" width="100%" alignItems="start">
            <Grid
              container
              direction="column"
              gap={SPACING.TINY}
              mt={SPACING.SMALL}
            >
              <Grid container xs={12} gap={2}>
                <TextField
                  label="جستجو بر اساس خریدار"
                  value={searchText}
                  onChange={(e) => setSearchText(e.target.value)}
                />
                <MyTable>
                  {sortedSlaughterReqs
                    ?.filter((item) => {
                      const buyerNamePrefix = item?.killHouse?.killer
                        ? "کشتارکن"
                        : "کشتارگاه";
                      const forSearch =
                        buyerNamePrefix + " " + item?.killHouse?.name;
                      return forSearch.includes(searchText);
                    })
                    .map((slaughterHouseReq, i) => {
                      return (
                        <SlaghterHouseRequestAllocationItem
                          name={i}
                          slaughterHouseReq={slaughterHouseReq}
                          avgLast4KillhousesWeight={avgLast4KillhousesWeight}
                          key={slaughterHouseReq?.name}
                          provinceCheckRequestKey={
                            file?.province?.provinceCheckRequestKey
                          }
                          poultryRequestKey={file?.poultry?.poultryRequestKey}
                          poultryRequestId={file?.poultry?.poultryRequestId}
                          file={file}
                          handleAllEntredQauntity={handleAllEntredQauntity}
                          allEntredQauntity={allEntredQauntity}
                          defaultValueForAllocate={defaultValueForAllocate}
                          updateTable={updateTable}
                        />
                      );
                    })}
                </MyTable>
              </Grid>

              {/* <Grid container direction="column" textAlign="initial">
                <FormControl>
                  <Typography variant="body1">نحوه فروش</Typography>
                  <RadioGroup
                    aria-labelledby="demo-radio-buttons-group-label"
                    name="radio-buttons-group"
                    onChange={(event) => {
                      formik.setFieldValue(
                        "paymentType",
                        event.currentTarget.value
                      );
                    }}
                  >
                    <FormControlLabel
                      value="cash"
                      control={<Radio />}
                      label="نقدی"
                    />
                    <FormControlLabel
                      value="credit"
                      control={<Radio />}
                      label="زمان دار (تا یک ماه)"
                    />
                  </RadioGroup>
                </FormControl>
              </Grid> */}
              {/* <Grid>
                <TextField
                  id="fee"
                  label="قیمت"
                  variant="outlined"
                  error={formik.touched.fee ? Boolean(formik.errors.fee) : null}
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  helperText={
                    formik.touched.fee && Boolean(formik.errors.fee)
                      ? formik.errors.fee
                      : null
                  }
                />
                <Grid
                  container
                  mt={SPACING.TINY}
                  gap={SPACING.TINY}
                  alignItems="center"
                >
                  <Typography
                    color={(prop) => prop.palette.grey["A700"]}
                    variant={"caption"}
                  >
                    قیمت مرغ استاندارد:
                  </Typography>
                  <Typography variant={"button"}>
                    {liveChickenPrice} ﷼
                  </Typography>
                </Grid>
                <Grid
                  container
                  mt={SPACING.TINY}
                  gap={SPACING.TINY}
                  alignItems="center"
                >
                  <Typography
                    color={(prop) => prop.palette.grey["A700"]}
                    variant={"caption"}
                  >
                    قیمت پیشنهادی:
                  </Typography>
                  <Typography variant={"button"}>{suggestPrice} ﷼</Typography>
                </Grid>
              </Grid> */}
            </Grid>
            {/* <Grid
              style={{
                background: file?.poultry?.clearanceCode
                  ? "#7aff7a"
                  : "#ff7a7a",
                padding: "10px",
                borderRadius: "5px",
                width: "100%",
                textAlign: "center",
              }}
              my={SPACING.SMALL}
            >
              <Typography fontWeight="bold" variant="body1">
                کدرهگیری سامانه قرنطینه:{" "}
                {file?.poultry?.clearanceCode
                  ? file?.poultry?.clearanceCode
                  : "در انتظار صدور"}
              </Typography>
            </Grid> */}
            <Grid textAlign={"start"} my={SPACING.SMALL}>
              <Typography fontWeight="bold" variant="body1">
                تخصیص های انجام شده
              </Typography>
            </Grid>
            {!allocationInformation?.provinceAssignments?.length && (
              <Typography textAlign={"start"} variant="body2">
                تخصیصی انجام نشده است.
              </Typography>
            )}
            {allocationInformation?.provinceAssignments?.map((item, i) => {
              let assignmentState;
              if (item.provinceKillRequestState === "accept") {
                assignmentState = "تایید شده است.";
              } else if (item.provinceKillRequestState === "pending") {
                assignmentState =
                  "در انتظار تایید و تخصیص خودرو توسط کشتارگاه می باشد.";
              } else if (item.provinceKillRequestState === "rejected") {
                assignmentState = "درخواست توسط کشتارگاه رد شده است!";
              }
              return (
                <Grid
                  container
                  gap={SPACING.MEDIUM}
                  alignItems={"center"}
                  mb={SPACING.SMALL}
                  key={i}
                >
                  <Grid gap={SPACING.TINY} container direction={"column"}>
                    <Grid container gap={SPACING.SMALL} alignItems={"center"}>
                      <Grid>
                        <Typography variant={"caption"}>
                          {item.killHouseName} / {item.killHouseUserName} /
                          {item.killHouseMobile}
                        </Typography>
                      </Grid>
                      <Grid>
                        <Typography variant={"caption"}>
                          تاریخ کشتار{" "}
                          {format(new Date(item.date), "yyyy/MM/dd")}
                        </Typography>
                      </Grid>
                      <Grid>
                        <Typography variant={"caption"}>
                          {item.mainQuantity?.toLocaleString()} قطعه
                        </Typography>
                      </Grid>
                      <Grid>
                        <Typography
                          variant={"caption"}
                          fontWeight="bold"
                          color="error"
                        >
                          {item?.market
                            ? "پنل معاملات"
                            : item.automaticState
                            ? "تخصیص خودکار"
                            : "تخصیص دستی"}
                        </Typography>
                      </Grid>
                    </Grid>
                    <Grid
                      textAlign={"start"}
                      container
                      gap={SPACING.TINY}
                      alignItems={"center"}
                    >
                      {item.provinceKillRequestState !== "rejected" ? (
                        <AccessTimeIcon color={"primary"} />
                      ) : (
                        <ThumbDownAltIcon color={"error"} />
                      )}

                      <Typography variant={"caption"}>
                        {assignmentState}
                      </Typography>
                    </Grid>
                  </Grid>
                  {item.provinceKillRequestState !== "rejected" &&
                    item?.returnToProvince === false && (
                      <Grid>
                        <Grid>
                          <Button
                            size={"small"}
                            variant="outlined"
                            color="error"
                            onClick={() => {
                              dispatch(
                                provinceRemoveAllocation({
                                  key: item.provinceKillRequestKey,
                                })
                              ).then((r) => {
                                if (r.error) {
                                  dispatch(LOADING_END());
                                  if (r.error.message.includes("403")) {
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: "به علت تایید کشتارگاه امکان حذف تخصیص وجود ندارد!",
                                      severity: "error",
                                    });
                                  } else {
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: "مشکلی پیش آمده است!",
                                      severity: "error",
                                    });
                                  }
                                } else {
                                  getFileFromApi(roles, id, dispatch);
                                  dispatch(
                                    getSlaughterHousesRequest(
                                      file?.poultry?.poultryRequestKey
                                    )
                                  );
                                  dispatch(
                                    provinceGetAllRequests(selectedDate1)
                                  );
                                  dispatch(
                                    getAllocationInformation({
                                      key: file?.poultry?.poultryRequestKey,
                                    })
                                  );
                                  openNotif({
                                    vertical: "top",
                                    horizontal: "center",
                                    msg: "عملیات با موفقیت انجام شد!",
                                    severity: "success",
                                  });
                                  updateTable();
                                }
                              });
                            }}
                          >
                            حذف
                          </Button>
                        </Grid>
                      </Grid>
                    )}
                </Grid>
              );
            })}
          </Grid>
        )}
        {allocateOrAuction === "auction" && (
          <Grid>
            <ProvinceAuction
              poultryRequestKey={file?.poultry?.poultryRequestKey}
            />
          </Grid>
        )}
      </Grid>
    </TimelineItem>
  );
};

ProvinceAllocation.propTypes = {
  file: PropTypes.object,
};
