import { Autocomplete } from "@mui/lab";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  FormControl,
  FormControlLabel,
  Radio,
  RadioGroup,
  TextField,
  Typography,
} from "@mui/material";
import React, { useEffect, useState } from "react";
import { PropTypes } from "prop-types";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import useSlaughterHousesRequest from "../../hooks/useSlaughterHousesRequest";
import useGetAllocationInformation from "../../hooks/useGetAllocationInformation";
import { SPACING } from "../../../../data/spacing";
import { useDispatch } from "react-redux";
import { provinceDoAllocation } from "../../services/province-do-allocation";
import { getSlaughterHousesForSelect } from "../../utils/getSlaughterHousesForSelect";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getAllocationInformation } from "../../services/get-allocation-information";
// 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 { getFileFromApi } from "../../hooks/useRequestFile";
import useUserProfile from "../../../authentication/hooks/useUserProfile";
import { useParams } from "react-router-dom";
import ThumbDownAltIcon from "@mui/icons-material/ThumbDownAlt";
import { avicultureGetChickenPrice } from "../../../aviculture/services/aviculture-get-chicken-price";
import { provinceRemoveAllocation } from "../../services/province-remove-allocation";

export const ProvinceAllocationContent = ({ file }) => {
  const [openNotif] = useContext(AppContext);

  const [selectedSlaughterHouseKey, setSelectedSlaughterHouseKey] =
    useState(null);

  const [requestedWeight, setRequestedWeight] = useState();
  const [requestedBuyType, setRequestedBuyType] = useState();

  // const [allocateOrAuction, setAllocateOrAuction] = useState("allocate");
  const [allocateOrAuction] = useState("allocate");

  const [slaughterAllocationLimit, setSlaughterAllocationLimit] = useState();

  const slaughterHousesRequest = useSlaughterHousesRequest(
    file.poultry.poultryRequestKey
  );

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

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

  const dispatch = useDispatch();
  const [roles] = useUserProfile();
  const { id } = useParams();

  // 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;
  // }

  // poultry sellType
  const requestedSellTypeCash = file.poultry.sellType.cash ? "نقدی" : null;
  const requestedSellTypeCredit = file.poultry.sellType.credit
    ? "زمان دار"
    : null;
  const requestedSellType = [requestedSellTypeCash, requestedSellTypeCredit]
    .filter((item) => item)
    .join(" یا ");

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

  const formik = useFormik({
    initialValues: {
      quantity: "",
      slaughterHouse: "",
      paymentType: "",
      // 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]);

  return (
    <>
      <Grid container direction="column" flexWrap="nowrap" flex="1">
        {/* <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" alignItems="start">
            <Grid
              container
              direction="column"
              gap={SPACING.TINY}
              mt={SPACING.SMALL}
            >
              <Grid>
                <Autocomplete
                  disablePortal
                  options={getSlaughterHousesForSelect(slaughterHousesRequest)}
                  id="slaughterHouse"
                  value={formik.values.slaughterHouse}
                  onChange={(e, option) => {
                    // if (e.target.nodeName === "svg") {
                    //   formik.setFieldValue("slaughterHouse", "");
                    // } else {
                    //   const target = e.target || e.srcElement;
                    formik.setFieldValue("slaughterHouse", e.target.outerText);
                    if (option?.key) {
                      setSelectedSlaughterHouseKey(option.key);
                    }
                    setSlaughterAllocationLimit(option.remainQuantity);
                    setRequestedWeight(option.requestedWeight);
                    setRequestedBuyType(option.requestedBuyType);
                    // }
                  }}
                  onBlur={formik.handleBlur}
                  sx={{ width: "100%", minWidth: 300 }}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label="کشتارگاه"
                      value={formik.values.slaughterHouse}
                      helperText={
                        formik.touched.slaughterHouse &&
                        Boolean(formik.errors.slaughterHouse)
                          ? formik.errors.slaughterHouse
                          : null
                      }
                      error={
                        formik.touched.slaughterHouse
                          ? Boolean(formik.errors.slaughterHouse)
                          : null
                      }
                    />
                  )}
                />
              </Grid>
              <Grid>
                <Grid container alignItems="center" gap={SPACING.SMALL}>
                  <Typography>مرغدار:</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"}>
                        {file.poultry.poultryIndexWeight}
                      </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"}>
                        {requestedSellType}
                      </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"}>
                        {file?.poultry?.killHouseList?.join(" - ")}
                      </Typography>
                    </Grid>
                  </Grid>
                </Grid>
                <Grid container alignItems="center" gap={SPACING.SMALL}>
                  <Typography>کشتارگاه:</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"}>
                        {requestedWeight}
                      </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"}>
                        {requestedBuyType}
                      </Typography>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
              <Grid>
                <TextField
                  id="quantity"
                  label="حجم"
                  variant="outlined"
                  error={
                    formik.touched.quantity
                      ? Boolean(formik.errors.quantity)
                      : null
                  }
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  helperText={
                    formik.touched.quantity && Boolean(formik.errors.quantity)
                      ? formik.errors.quantity
                      : null
                  }
                />
                <Grid
                  container
                  mt={SPACING.TINY}
                  gap={SPACING.TINY}
                  alignItems="center"
                >
                  <Typography
                    color={(prop) => prop.palette.grey["A700"]}
                    variant={"caption"}
                  >
                    مانده درخواست
                  </Typography>
                  <Typography variant={"button"}>
                    {allocationInformation.quantity - formik.values.quantity >=
                    0
                      ? allocationInformation.quantity - formik.values.quantity
                      : allocationInformation.quantity}{" "}
                    قطعه
                  </Typography>
                </Grid>
              </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>
                <Button
                  size={"large"}
                  variant="contained"
                  disabled={!formik.isValid}
                  onClick={() => {
                    dispatch(LOADING_START());
                    dispatch(
                      provinceDoAllocation({
                        kill_request_key: selectedSlaughterHouseKey,
                        province_check_request_key:
                          file.province.provinceCheckRequestKey,
                        quantity: formik.values.quantity,
                        payment_type: formik.values.paymentType,
                        // fee: formik.values.fee,
                      })
                    ).then((r) => {
                      dispatch(LOADING_END());
                      dispatch(
                        getAllocationInformation({
                          key: file.poultry.poultryRequestKey,
                        })
                      );
                      if (r.error) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "مشکلی پیش آمده است!",
                          severity: "error",
                        });
                      } else {
                        getFileFromApi(roles, id, dispatch);
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "عملیات با موفقیت انجام شد.",
                          severity: "success",
                        });
                      }
                    });
                  }}
                >
                  ثبت اطلاعات
                </Button>
              </Grid>
            </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.quantity} قطعه
                        </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" && (
                    <Grid>
                      <Grid>
                        <Button
                          size={"small"}
                          variant="outlined"
                          color="error"
                          onClick={() => {
                            dispatch(
                              provinceRemoveAllocation({
                                key: item.provinceKillRequestKey,
                              })
                            ).then((r) => {
                              if (r.error) {
                                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);
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: "عملیات با موفقیت انجام شد!",
                                  severity: "success",
                                });
                              }
                            });
                          }}
                        >
                          حذف
                        </Button>
                      </Grid>
                    </Grid>
                  )}
                </Grid>
              );
            })}
          </Grid>
        )}
        {allocateOrAuction === "auction" && (
          <Grid>
            <ProvinceAuction
              poultryRequestKey={file.poultry.poultryRequestKey}
            />
          </Grid>
        )}
      </Grid>
    </>
  );
};

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