import React, { useContext } from "react";
import {
  Grid,
  TextField,
  Button,
  RadioGroup,
  FormControlLabel,
  Radio,
  FormControl,
} from "@mui/material";
import { useFormik } from "formik";
import * as Yup from "yup";
import { useDispatch } from "react-redux";
import { guildAllocatedStockOperationService } from "../services/guild-allocated-stock-operation";
import { AppContext } from "../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../lib/redux/slices/appSlice";

export const StewardNorEnterdBarChangeState = ({
  item,
  handleUpdate,
  updateTable,
}) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      decision: "approve",
      weight: item?.realWeightOfCarcasses,
      volume: item?.realNumberOfCarcasses,
      weightLoss: item?.weightLossOfCarcasses,
      regCode: "",
      regState: "with_code",
    },
    validationSchema: Yup.object({
      decision: Yup.string().required("انتخاب گزینه الزامی است"),
      regState: Yup.string(),
      weight: Yup.string().when("decision", {
        is: "approve",
        then: Yup.string().required("وزن الزامی است"),
      }),
      volume: Yup.string().when("decision", {
        is: "approve",
        then: Yup.string().required("حجم الزامی است"),
      }),
      weightLoss: Yup.string().when("decision", {
        is: "approve",
        then: Yup.string().required("افت وزن الزامی است"),
      }),
      regCode: Yup.string()
        .matches(/^\d{5}$/, "کد باید یک عدد پنج رقمی باشد")
        .typeError("یک عدد پنج رقمی وارد کنید!")
        .when(["regState", "decision"], {
          is: (regState, decision) =>
            regState === "with_code" && decision === "approve",
          then: Yup.string().required("کد احراز الزامی است"),
        }),
    }),
    onSubmit: (values) => {
      const baseRequest = {
        check_allocation: true,
        allocation_key: item?.key,
      };

      const req =
        values.decision === "reject"
          ? { ...baseRequest, state: "rejected" }
          : {
              ...baseRequest,
              state: "accepted",
              ...(values.regState === "with_code" && {
                registration_code: parseInt(values.regCode),
              }),
              receiver_real_number_of_carcasses: parseInt(values.volume),
              receiver_real_weight_of_carcasses: parseInt(values.weight),
              weight_loss_of_carcasses: parseInt(values.weightLoss),
            };

      dispatch(guildAllocatedStockOperationService(req)).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());
          handleUpdate();
          updateTable && updateTable();
        }
      });
    },
  });

  const handleDecisionChange = (event) => {
    formik.setFieldValue("decision", event.target.value);
  };

  return (
    <Grid container spacing={2} justifyContent="center" alignItems="center">
      <Grid item xs={12}>
        <FormControl component="fieldset">
          <RadioGroup
            fullWidth
            row
            name="decision"
            value={formik.values.decision}
            onChange={handleDecisionChange}
          >
            <FormControlLabel
              value="approve"
              control={<Radio />}
              label="تایید"
            />
            <FormControlLabel value="reject" control={<Radio />} label="رد" />
          </RadioGroup>
        </FormControl>
        {formik.touched.decision && formik.errors.decision && (
          <div style={{ color: "red", fontSize: 12 }}>
            {formik.errors.decision}
          </div>
        )}
      </Grid>

      {formik.values.decision === "approve" && (
        <>
          <Grid item xs={12}>
            <TextField
              fullWidth
              name="weight"
              label="وزن"
              value={formik.values.weight}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              error={formik.touched.weight && Boolean(formik.errors.weight)}
              helperText={formik.touched.weight && formik.errors.weight}
            />
          </Grid>
          <Grid item xs={12}>
            <TextField
              fullWidth
              name="volume"
              label="حجم"
              value={formik.values.volume}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              error={formik.touched.volume && Boolean(formik.errors.volume)}
              helperText={formik.touched.volume && formik.errors.volume}
            />
          </Grid>
          <Grid item xs={12}>
            <TextField
              fullWidth
              name="weightLoss"
              label="افت وزن (کیلوگرم)"
              value={formik.values.weightLoss}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              error={
                formik.touched.weightLoss && Boolean(formik.errors.weightLoss)
              }
              helperText={formik.touched.weightLoss && formik.errors.weightLoss}
            />
          </Grid>
          <Grid item xs={12}>
            <FormControl component="fieldset">
              <RadioGroup
                fullWidth
                row
                name="regState"
                value={formik.values.regState}
                onChange={(e) => {
                  formik.setFieldValue("regState", e.target.value);
                }}
              >
                <FormControlLabel
                  value="with_code"
                  control={<Radio />}
                  label="با کد احراز"
                />
                <FormControlLabel
                  value="without_code"
                  control={<Radio />}
                  label="بدون کد احراز"
                />
              </RadioGroup>
            </FormControl>
            {formik.touched.regState && formik.errors.regState && (
              <div style={{ color: "red", fontSize: 12 }}>
                {formik.errors.regState}
              </div>
            )}
          </Grid>
          {formik.values.regState === "with_code" && (
            <Grid item xs={12}>
              <TextField
                fullWidth
                name="regCode"
                label="کد احراز"
                value={formik.values.regCode}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                error={formik.touched.regCode && Boolean(formik.errors.regCode)}
                helperText={formik.touched.regCode && formik.errors.regCode}
              />
            </Grid>
          )}
        </>
      )}

      <Grid item xs={12}>
        <Button
          onClick={formik.handleSubmit}
          type="submit"
          variant="contained"
          color={formik.values.decision === "approve" ? "primary" : "error"}
          fullWidth
        >
          ثبت
        </Button>
      </Grid>
    </Grid>
  );
};
