import {
  Button,
  Divider,
  FormControl,
  FormHelperText,
  IconButton,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Typography,
} from "@mui/material";
import { useFormik } from "formik";
import moment from "moment";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { PropTypes } from "prop-types";

import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { Yup } from "../../../../lib/yup/yup";
import { avicultureGetChickenPrice } from "../../../aviculture/services/aviculture-get-chicken-price";
import { avicultureGetRequests } from "../../../aviculture/services/aviculture-requests";
import DeleteIcon from "@mui/icons-material/Delete";
import AddIcon from "@mui/icons-material/Add";
import { provinceRequestAuction } from "../../services/province-request-auction";
import { AppContext } from "../../../../contexts/AppContext";
import { getFileFromApi } from "../../hooks/useRequestFile";
import { useParams } from "react-router-dom";
import useUserProfile from "../../../authentication/hooks/useUserProfile";

export const ProvinceAuction = ({ poultryRequestKey }) => {
  const [pricingKey, setPriceKey] = useState();
  const { id } = useParams();
  const [roles] = useUserProfile();

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

  const [openNotif] = useContext(AppContext);

  const dispatch = useDispatch();

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

  const [arr, setArr] = useState([
    {
      id: 0,
      value: "",
      hour: 2,
    },
  ]);

  const addInput = () => {
    setArr((prevState) => {
      return [
        ...prevState,
        {
          id: prevState.length,
          value: "",
          hour: 1,
        },
      ];
    });
  };

  const removeInput = (e) => {
    let number = arr.length - 1;

    if (number !== 0) {
      let filteredArrayPrice = arr.filter((object, i) => i < number);
      // let filteredArrayTime = arrPrices.filter((object, i) => i < number);

      setArr(filteredArrayPrice);
      // setArrPrices(filteredArrayTime);
    }
  };

  const handleChange = (e) => {
    const [itemName, itemIndex] = e.target.name.split("-");
    if (itemName === "price") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].value = e.target.value;
        return newState;
      });
    } else if (itemName === "hour") {
      setArr((prevState) => {
        const newState = prevState;
        newState[itemIndex].hour = Number(e.target.value);
        return newState;
      });
    }
  };
  useEffect(() => {
    if (avicultureChickenPrice) {
      setPriceKey(avicultureChickenPrice.key);
    }
  }, [avicultureChickenPrice]);

  const formik = useFormik({
    initialValues: {
      noChicken: "",
      price1: "",
      price2: "",
      price3: "",
      slaughterDate: moment(Date()).format("YYYY-MM-DD hh:mm:ss"),
      period1: "4",
      period2: "4",
      period3: "4",
      weight: "",
    },
    validationSchema: Yup.object({
      price1: Yup.number()
        .typeError("لطفا عدد وارد کنید!")
        .min(
          avicultureChickenPrice?.floorPrice,
          "قیمت وارد شده از کف قیمت امروز کمتر است"
        )
        .max(
          avicultureChickenPrice?.ceilingPrice,
          "قیمت وارد شده از سقف قیمت امروز بیشتر است"
        ),
      price2: Yup.number()
        .typeError("لطفا عدد وارد کنید!")
        .min(
          avicultureChickenPrice?.floorPrice,
          "قیمت وارد شده از کف قیمت امروز کمتر است"
        )
        .max(
          avicultureChickenPrice?.ceilingPrice,
          "قیمت وارد شده از سقف قیمت امروز بیشتر است"
        ),
      price3: Yup.number()
        .typeError("لطفا عدد وارد کنید!")
        .min(
          avicultureChickenPrice?.floorPrice,
          "قیمت وارد شده از کف قیمت امروز کمتر است"
        )
        .max(
          avicultureChickenPrice?.ceilingPrice,
          "قیمت وارد شده از سقف قیمت امروز بیشتر است"
        ),
      weight: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا وزن را وارد کنید!"),
    }),
  });

  return (
    <Grid container gap={SPACING.SMALL}>
      <Grid container gap={SPACING.SMALL} alignItems={"center"}>
        <Typography
          color={(prop) => prop.palette.grey["A700"]}
          variant={"caption"}
        >
          کف قیمت امروز:
        </Typography>
        <Typography color="secondary" variant={"button"}>
          {avicultureChickenPrice?.floorPrice
            ? avicultureChickenPrice?.floorPrice.toLocaleString()
            : "نامشخص"}{" "}
          {"  "}
          ریال
        </Typography>
      </Grid>
      <Grid container gap={SPACING.SMALL} alignItems={"center"}>
        <Typography
          color={(prop) => prop.palette.grey["A700"]}
          variant={"caption"}
        >
          سقف قیمت امروز:
        </Typography>
        <Typography color="secondary" variant={"button"}>
          {avicultureChickenPrice?.ceilingPrice
            ? avicultureChickenPrice?.ceilingPrice.toLocaleString()
            : "نامشخص"}{" "}
          {"  "}
          ریال
        </Typography>
      </Grid>

      <Divider style={{ width: "100%" }} />
      <Grid container direction="column">
        <Grid
          container
          direction="column"
          gap={SPACING.SMALL}
          alignItems="start"
        >
          <Grid container gap={SPACING.MEDIUM} alignItems="center">
            {arr.map((item, i) => {
              return (
                <Grid gap={SPACING.SMALL} container key={i}>
                  <Typography variant="body2" fontWeight="bold">
                    پیشنهاد {i + 1}
                  </Typography>
                  <TextField
                    error={false}
                    fullWidth
                    label="قیمت پیشنهادی"
                    variant="outlined"
                    onChange={handleChange}
                    name={"price-" + i}
                  />
                  <FormControl fullWidth>
                    <InputLabel id="demo-simple-select-label">
                      بازه زمانی (ساعت)
                    </InputLabel>
                    <Select
                      labelId="demo-simple-select-label"
                      label="بازه زمانی (ساعت)"
                      name={"hour-" + i}
                      onChange={handleChange}
                    >
                      <MenuItem value={"1"}>1</MenuItem>
                      <MenuItem value={"2"}>2</MenuItem>
                      <MenuItem value={"3"}>3</MenuItem>
                      <MenuItem value={"4"}>4</MenuItem>
                      <MenuItem value={"5"}>5</MenuItem>
                      <MenuItem value={"6"}>6</MenuItem>
                      <MenuItem value={"7"}>7</MenuItem>
                      <MenuItem value={"8"}>8</MenuItem>
                      <MenuItem value={"9"}>9</MenuItem>
                      <MenuItem value={"10"}>10</MenuItem>
                    </Select>
                    <FormHelperText>
                      {formik.touched.period1 && Boolean(formik.errors.period1)
                        ? formik.errors.period1
                        : null}
                    </FormHelperText>
                  </FormControl>
                  {/* <input
              key={i}
              onChange={handleChange}
              value={item.value}
              id={i}
              type={item.type}
            /> */}
                </Grid>
              );
            })}
            <Grid container direction="column">
              <IconButton aria-label="delete" color="secondary">
                <DeleteIcon onClick={removeInput} />
              </IconButton>
              <IconButton aria-label="delete" color="success">
                <AddIcon onClick={addInput} />
              </IconButton>
            </Grid>
          </Grid>
        </Grid>
      </Grid>
      <Button
        fullWidth
        disabled={!formik.isValid}
        onClick={() => {
          dispatch(LOADING_START());
          dispatch(
            provinceRequestAuction({
              poultry_request_key: poultryRequestKey,
              auction_list: arr.map((item, i) => {
                return {
                  pricing_key: pricingKey,
                  fee: item.value,
                  hour: item.hour,
                };
              }),
            })
          ).then((r) => {
            dispatch(LOADING_END());
            if (r.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                severity: "error",
                msg: "مشکلی پیش آمده است!",
              });
            } else {
              dispatch(avicultureGetRequests());
              getFileFromApi(roles, id, dispatch);
              openNotif({
                vertical: "top",
                horizontal: "center",
                severity: "success",
                msg: "با موفقیت انجام شد!",
              });
              dispatch(DRAWER({ right: false, bottom: false, content: null }));
            }
          });
        }}
        size="large"
        variant="contained"
      >
        ثبت درخواست
      </Button>
    </Grid>
  );
};

ProvinceAuction.propTypes = {
  poultryRequestKey: PropTypes.any,
};
