import React, { useContext } from "react";
import { useFormik } from "formik";
import * as Yup from "yup";
import {
  Radio,
  RadioGroup,
  FormControlLabel,
  FormControl,
  TextField,
  Button,
  Typography,
} from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch } from "react-redux";
import { cityEditHatchingQuantityService } from "../../../city/services/city-edit-hatching-quantity";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

export const VetFarmSubmitFarmInfoLosses = ({ item, updateTable }) => {
  const dispatch = useDispatch();

  const [openNotif] = useContext(AppContext);
  const formik = useFormik({
    initialValues: {
      lossType: "aggregate",
      lossVolume: "",
    },
    validationSchema: Yup.object({
      lossType: Yup.string().required("لطفاً نوع خسارت را انتخاب کنید."),
      lossVolume: Yup.string()
        .required("لطفاً حجم تلفات را وارد کنید.")
        .matches(/^\d+$/, "حجم تلفات باید عدد باشد."),
    }),
    onSubmit: (values) => {
      dispatch(
        cityEditHatchingQuantityService({
          key: item?.key,
          end_period_losses: true,
          type: values.lossType,
          losses: parseInt(values.lossVolume),
        })
      ).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",
          });
          updateTable();
          dispatch(CLOSE_MODAL());
        }
      });
    },
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container xs={12} alignItems="center" spacing={2}>
        <Grid item xs={12}>
          <FormControl component="fieldset" fullWidth>
            <RadioGroup
              row
              name="lossType"
              value={formik.values.lossType}
              onChange={formik.handleChange}
            >
              <FormControlLabel
                value="aggregate"
                control={<Radio />}
                label="کل تلفات دوره (پایان کار)"
              />
              <FormControlLabel
                value="add"
                control={<Radio />}
                label="افزودن به تلفات دامپزشک فارم"
              />
            </RadioGroup>
            {formik.touched.lossType && formik.errors.lossType && (
              <div style={{ color: "red", fontSize: "0.8em" }}>
                {formik.errors.lossType}
              </div>
            )}
          </FormControl>
        </Grid>

        <Grid container item xs={12}>
          <TextField
            fullWidth
            name="lossVolume"
            label="حجم تلفات"
            value={formik.values.lossVolume}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.lossVolume && Boolean(formik.errors.lossVolume)
            }
            helperText={formik.touched.lossVolume && formik.errors.lossVolume}
          />
        </Grid>

        {formik.values.lossType === "aggregate" && (
          <Typography variant="body2" color="error" mx={2} mt={1}>
            اخطار: تلفات وارد شده جایگزین کل تلفات خواهد شد!
          </Typography>
        )}

        <Grid item xs={12}>
          <Button type="submit" variant="contained" color="primary" fullWidth>
            ثبت اطلاعات
          </Button>
        </Grid>
      </Grid>
    </form>
  );
};
