import React, { useContext, useEffect, useState } from "react";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { Grid } from "../../../../components/grid/Grid";
import { Button, TextField, Typography } from "@mui/material";
import {
  CLOSE_MODAL,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { SPACING } from "../../../../data/spacing";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";

import { slaughterEditFreeSaleService } from "../../services/slaughter-edit-free-sale";
import { fetchSlaughterBroadcastAndProducts } from "../../services/handle-fetch-slaughter-products";

export const SlaughterSubmitRealInventoryFreeBar = ({ item, updateTable }) => {
  const [loss, setLoss] = useState("0");

  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      realNumber: item.numberOfCarcasses ? item.numberOfCarcasses : "",
      realWeight: item.weightOfCarcasses ? item.weightOfCarcasses : "",
    },
    validationSchema: Yup.object({
      realNumber: Yup.number()
        .typeError("لطفا فیلد را به درستی وارد کنید.!")
        .required("این فیلد اجباری است!"),
      realWeight: Yup.number()
        .typeError("لطفا فیلد را به درستی وارد کنید.!")
        .required("این فیلد اجباری است!"),
    }),
  });

  useEffect(() => {
    let difference = item?.liveWeight - formik.values.realWeight;
    if (difference < item?.liveWeight) {
      setLoss(((difference / item?.liveWeight) * 100).toPrecision(4));
    } else {
      setLoss(0);
    }

    formik.setFieldValue(
      "realNumber",
      Math.round(formik.values.realWeight / 1.5)
    );
  }, [formik.values.realWeight]);

  const handleAlert = () => {
    dispatch(
      OPEN_MODAL({
        title: "عملیات با موفقیت انجام شد",
        content: (
          <>
            <Grid container gap={SPACING.SMALL} justifyContent="center">
              <Typography variant="body2" color="secondary">
                جهت ویرایش میتوانید حداکثر تا پایان امروز یا قبل از اولین تخصیص
                اقدام کنید.
              </Typography>
              <Button
                variant="outlined"
                onClick={() => {
                  dispatch(CLOSE_MODAL());
                }}
              >
                متوجه شدم
              </Button>
            </Grid>
          </>
        ),
      })
    );
  };

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

  return (
    <>
      <Grid
        xs={12}
        container
        spacing={SPACING.SMALL}
        alignItems="center"
        justifyContent="center"
      >
        <Grid container xs={12} gap={SPACING.TINY}>
          <Grid container xs={12} gap={SPACING.SMALL} justifyContent="center">
            <Typography color="primary" variant="body2">
              وزن بار زنده: {item?.liveWeight?.toLocaleString()} کیلوگرم
            </Typography>
          </Grid>

          <TextField
            fullWidth
            id="realWeight"
            size="small"
            label="وزن لاشه"
            variant="outlined"
            value={formik.values.realWeight}
            error={
              formik.touched.realWeight
                ? Boolean(formik.errors.realWeight)
                : null
            }
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.realWeight && Boolean(formik.errors.realWeight)
                ? formik.errors.realWeight
                : null
            }
          />

          <TextField
            fullWidth
            id="realNumber"
            size="small"
            label="حجم لاشه"
            variant="outlined"
            value={formik.values.realNumber}
            error={
              formik.touched.realNumber
                ? Boolean(formik.errors.realNumber)
                : null
            }
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.realNumber && Boolean(formik.errors.realNumber)
                ? formik.errors.realNumber
                : null
            }
          />
        </Grid>
        <Grid
          container
          xs={12}
          gap={4}
          alignItems="center"
          mt={2}
          justifyContent="space-between"
        >
          <Grid>
            <Typography variant="body1" color="primary">
              افت: {loss > 0 ? loss : 0}%
            </Typography>
            {(loss > 30 || loss < 20) && (
              <Typography variant="body2" color="error">
                درصد افت باید بین 20 تا 30 درصد باشد!
              </Typography>
            )}
          </Grid>
          <Grid>
            <Button
              disabled={!formik.isValid || loss > 30 || loss < 20}
              size="small"
              variant="outlined"
              onClick={() => {
                dispatch(LOADING_START());
                dispatch(
                  slaughterEditFreeSaleService({
                    key: item?.key,
                    number_of_carcasses: Number(formik.values.realNumber),
                    weight_of_carcasses: Number(formik.values.realWeight),
                    ware_house: true,
                    weight_loss: parseFloat(loss),
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    dispatch(CLOSE_MODAL());
                    updateTable(1);
                    handleAlert();
                    dispatch(fetchSlaughterBroadcastAndProducts());
                  }
                });
              }}
            >
              ثبت
            </Button>
          </Grid>
        </Grid>
      </Grid>
    </>
  );
};
