import {
  Button,
  Checkbox,
  Divider,
  FormControl,
  FormControlLabel,
  Radio,
  RadioGroup,
  TextField,
  Typography,
} from "@mui/material";
import { useContext, useEffect, useState } from "react";
import { Grid } from "../../../components/grid/Grid";
import { SPACING } from "../../../data/spacing";
import { Yup } from "../../../lib/yup/yup";
import { useFormik } from "formik";
import { guildAllocatedStockOperationService } from "../services/guild-allocated-stock-operation";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../contexts/AppContext";
import { guildGetInventoryStockService } from "../services/guild-get-inventory-stock";
import { guildGetInventoryAllocatedService } from "../services/guild-get-inventory-allocated";
import { CLOSE_MODAL } from "../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../utils/getRoleFromUrl";
import { senfGetInventoryStockService } from "../services/senf-get-inventory-stock";
import { senfGetInventoryAllocatedService } from "../services/senf-get-inventory-allocated";

export const GuildReceiveBarOperation = ({ item, onSuccess }) => {
  const dispatch = useDispatch();
  const [, , selectedDate1] = useContext(AppContext);
  const [openNotif] = useContext(AppContext);
  const [selectedValue, setSelectedValue] = useState("option1");

  const handleChange = (event) => {
    setSelectedValue(event.target.value);
  };

  const initialValues = {
    authCode: "",
  };

  const validationSchema = Yup.object({
    authCode: Yup.string().required("کداحراز اجباری است"),
  });

  const formik = useFormik({
    initialValues,
    validationSchema,
  });

  const [isChecked, setChecked] = useState(false);

  const handleCheckboxChange = () => {
    setChecked(!isChecked);
  };

  const formikRealInfo = useFormik({
    initialValues: {
      number: "",
      weight: "",
    },
    validationSchema: Yup.object({
      weight: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا وزن را وارد کنید!"),
    }),
  });

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

  return (
    <Grid
      container
      width="100%"
      direction="column"
      justifyContent="space-between"
      gap={SPACING.TINY}
    >
      <Grid container justifyContent="space-around">
        <Typography variant="caption">
          وزن تخصیصی: {item.weightOfCarcasses.toLocaleString()} کیلوگرم
        </Typography>
        <Typography variant="caption">
          تعداد تخصیصی: {item.numberOfCarcasses.toLocaleString()} قطعه
        </Typography>
      </Grid>
      <Divider />

      <Grid container spacing={1} alignItems="center">
        <Grid item>
          <FormControlLabel
            control={
              <Checkbox
                size="small"
                checked={isChecked}
                onChange={handleCheckboxChange}
              />
            }
            label="ثبت تعداد واقعی تحویلی"
          />
        </Grid>
        <Grid container xs={12} spacing={1}>
          <Grid item xs={6}>
            <TextField
              id="weight"
              size="small"
              label="وزن"
              variant="outlined"
              fullWidth
              disabled={!isChecked}
              onChange={formikRealInfo.handleChange}
              onBlur={formikRealInfo.handleBlur}
              value={formikRealInfo.values.weight}
              error={
                formikRealInfo.touched.weight &&
                Boolean(formikRealInfo.errors.weight)
              }
              helperText={
                formikRealInfo.touched.weight
                  ? formikRealInfo.errors.weight
                  : ""
              }
            />
          </Grid>
        </Grid>
      </Grid>
      <FormControl component="fieldset">
        <RadioGroup
          row
          aria-label="radio-buttons-group"
          name="radio-buttons-group"
          value={selectedValue}
          onChange={handleChange}
          style={{ justifyContent: "space-between", flexDirection: "row" }}
        >
          <FormControlLabel
            value="option1"
            control={<Radio />}
            label="تحویل بار با کداحراز"
          />
          <FormControlLabel
            value="option2"
            control={<Radio />}
            label="تحویل بار بدون کداحراز"
          />
        </RadioGroup>
      </FormControl>

      {selectedValue === "option1" && (
        <TextField
          fullWidth
          id="authCode"
          name="authCode"
          label="کداحراز"
          variant="outlined"
          margin="normal"
          onChange={formik.handleChange}
          onBlur={formik.handleBlur} // Add onBlur to track touched state
          value={formik.values.authCode}
          error={formik.touched.authCode && Boolean(formik.errors.authCode)}
          helperText={formik.touched.authCode ? formik.errors.authCode : ""}
        />
      )}
      <Button
        disabled={
          (selectedValue === "option1" ? !formik.isValid : false) ||
          (isChecked ? !formikRealInfo.isValid : false)
        }
        variant="contained"
        onClick={() => {
          let reqObj = {};
          if (formik.values.authCode) {
            if (getRoleFromUrl() === "senf") {
              reqObj = {
                guild_check_allocation: true,
                receiver_real_number_of_carcasses: 0,
                receiver_real_weight_of_carcasses: formikRealInfo.values.weight
                  ? formikRealInfo.values.weight
                  : item.weightOfCarcasses,
                allocation_key: item.key,
                registration_code: Number(formik.values.authCode),
                state: "accepted",
              };
            } else {
              reqObj = {
                steward_check_allocation: true,
                allocation_key: item.key,
                receiver_real_number_of_carcasses: 0,
                receiver_real_weight_of_carcasses: formikRealInfo.values.weight
                  ? formikRealInfo.values.weight
                  : item.weightOfCarcasses,
                registration_code: Number(formik.values.authCode),
                state: "accepted",
              };
            }
          } else {
            if (getRoleFromUrl() === "senf") {
              reqObj = {
                guild_check_allocation: true,
                allocation_key: item.key,
                receiver_real_number_of_carcasses: 0,
                receiver_real_weight_of_carcasses: formikRealInfo.values.weight
                  ? formikRealInfo.values.weight
                  : item.weightOfCarcasses,
                state: "accepted",
              };
            } else {
              reqObj = {
                steward_check_allocation: true,
                allocation_key: item.key,
                receiver_real_number_of_carcasses: 0,
                receiver_real_weight_of_carcasses: formikRealInfo.values.weight
                  ? formikRealInfo.values.weight
                  : item.weightOfCarcasses,
                state: "accepted",
              };
            }
          }

          dispatch(guildAllocatedStockOperationService(reqObj)).then((r) => {
            if (r.payload.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: r.payload.error,
                severity: "error",
              });
            } else {
              if (getRoleFromUrl() === "senf") {
                dispatch(
                  senfGetInventoryStockService({
                    date: selectedDate1,
                  })
                );
                dispatch(
                  senfGetInventoryAllocatedService({
                    date: selectedDate1,
                  })
                );
              } else {
                dispatch(
                  guildGetInventoryStockService({
                    date: selectedDate1,
                  })
                );
                dispatch(
                  guildGetInventoryAllocatedService({
                    date: selectedDate1,
                  })
                );
              }
              onSuccess?.();
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
              });
              dispatch(CLOSE_MODAL());
            }
          });
        }}
      >
        تحویل بار
      </Button>
      <Button
        variant="contained"
        color="error"
        onClick={() => {
          dispatch(
            guildAllocatedStockOperationService({
              steward_check_allocation: true,
              allocation_key: item.key,
              state: "rejected",
            })
          ).then((r) => {
            if (r.payload.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: r.payload.error,
                severity: "error",
              });
            } else {
              if (getRoleFromUrl() === "senf") {
                dispatch(
                  senfGetInventoryStockService({
                    date: selectedDate1,
                  })
                );
                dispatch(
                  senfGetInventoryAllocatedService({
                    date: selectedDate1,
                  })
                );
              } else {
                dispatch(
                  guildGetInventoryStockService({
                    date: selectedDate1,
                  })
                );
                dispatch(
                  guildGetInventoryAllocatedService({
                    date: selectedDate1,
                  })
                );
              }
              onSuccess?.();
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
              });
              dispatch(CLOSE_MODAL());
            }
          });
        }}
      >
        رد بار
      </Button>
    </Grid>
  );
};
