import React, { useContext } from "react";
import { TextField, Button, Typography, Divider } from "@mui/material";
import { useFormik } from "formik";
import * as Yup from "yup";
import { useDispatch, useSelector } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { slaughterEditChickenPriceService } from "../../services/slaughter-edit-chicken-price";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const SlaughterSubmitChickenPrice = ({ fetchData, item }) => {
  const dispatch = useDispatch();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const [openNotif] = useContext(AppContext);

  const formik = useFormik({
    initialValues: {
      chickenPrice: "",
    },
    validationSchema: Yup.object({
      chickenPrice: Yup.number()
        .required("این فیلد اجباری است!")
        .positive("مقدار مثبت وارد کنید!")
        .typeError("لطفا عدد وارد کنید!")
        .min(
          item?.freeSaleInProvince ? 400000 : (item?.amount / 100) * 40,
          item?.freeSaleInProvince
            ? "حداقل قیمت قابل ثبت چهل هزار تومان است!"
            : "اختلاف قیمت وارد شده و قیمت مرغدار باید کمتر از شصت درصد باشد!"
        )
        .max(
          item?.freeSaleInProvince
            ? 2000000
            : (item?.amount / 100) * 60 + item?.amount,
          item?.freeSaleInProvince
            ? "قیمت متعارف وارد کنید!"
            : "اختلاف قیمت وارد شده و قیمت مرغدار باید کمتر از شصت درصد باشد!"
        ),
    }),
    onSubmit: (values) => {
      dispatch(
        slaughterEditChickenPriceService({
          province_kill_request_key: item?.provinceKillReqKey,
          kill_house_price: values.chickenPrice,
          role: getRoleFromUrl(),
          role_key: checkPathStartsWith("slaughter")
            ? selectedSubUser?.key || ""
            : "",
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
          dispatch(CLOSE_MODAL());
          fetchData();
        }
      });
    },
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <Typography variant="body1" color="primary" mb={1}>
        اطلاعات سفارش
      </Typography>
      <Divider style={{ width: "100%" }} />

      <Grid container xs={12} gap={1} mt={1}>
        <Typography variant="body2" style={{ color: "gray" }}>
          نام مرغدار:
        </Typography>
        <Typography variant="body2" color="primary">
          {`${item.poultryName} (${item.poultryMobile})`}
        </Typography>
      </Grid>

      <Grid container xs={12} gap={1}>
        <Typography variant="body2" style={{ color: "gray" }}>
          قیمت مرغدار:
        </Typography>
        <Typography variant="body2" color="primary">
          {item.amount.toLocaleString() + " ﷼"}
        </Typography>
      </Grid>
      <Grid container xs={12} gap={1}>
        <Typography variant="body2" style={{ color: "gray" }}>
          میانگین وزنی:
        </Typography>
        <Typography variant="body2" color="primary">
          {item?.indexWeight + " کیلوگرم"}
        </Typography>
      </Grid>
      <Grid container xs={12} gap={1}>
        <Typography variant="body2" style={{ color: "gray" }}>
          حجم تخصیص:
        </Typography>
        <Typography variant="body2" color="primary">
          {item.mainQuantity.toLocaleString() + " قطعه"}
        </Typography>
      </Grid>

      <TextField
        style={{ minWidth: "350px" }}
        fullWidth
        id="chickenPrice"
        name="chickenPrice"
        label="قیمت خرید هر کیلو مرغ زنده را ثبت کنید"
        value={formik.values.chickenPrice}
        onChange={formik.handleChange}
        error={
          formik.touched.chickenPrice && Boolean(formik.errors.chickenPrice)
        }
        helperText={formik.touched.chickenPrice && formik.errors.chickenPrice}
        margin="normal"
      />
      <Button color="primary" variant="contained" fullWidth type="submit">
        ثبت
      </Button>
    </form>
  );
};
