import {
  Button,
  FormControl,
  FormControlLabel,
  FormLabel,
  Radio,
  RadioGroup,
  TextField,
  Typography,
} from "@mui/material";
import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { provinceCheckFreeSaleService } from "../../services/province-check-free-sale";
import { provinceGetFreeSalesRequestsService } from "../../services/province-get-free-sales-requests";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { provinceEditFreeSaleService } from "../../services/province-edit-free-sale";
import { useProvinceName } from "../../../../utils/getProvinceName";

export const ProvinceCheckFreeSale = ({
  buyer,
  poultryRequestKey,
  item,
  isEdit,
}) => {
  const [, , selectedDate1, , selectedDate2] = useContext(AppContext);

  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [value, setValue] = useState("");
  const [payerValue, setPayerValue] = useState(
    isEdit ? item.payerType : "poultry"
  );
  const handleChange = (event) => {
    setValue(event.target.value);
  };

  const provinceName = useProvinceName();

  const handleChangePayer = (event) => {
    setPayerValue(event.target.value);
    if (event.target.value === "buyer") {
      formik.setFieldValue("mobile", buyer.mobile);
    } else {
      formik.setFieldValue("mobile", item.poultry.user.mobile);
    }
  };

  const formik = useFormik({
    initialValues: {
      mobile: item.poultry.user.mobile,
      weight: isEdit ? item?.IndexWeight : "",
      quantity: isEdit ? item?.quantity : "",
    },
    validationSchema: Yup.object({
      mobile: Yup.string()
        .required("شماره موبایل الزامی است")
        .min(11, "شماره موبایل باید 11 رقم باشد")
        .max(11, "شماره موبایل باید 11 رقم باشد")
        .matches(/^09\d{9}$/, "شماره موبایل باید با 09 شروع شود و 11 رقم باشد"),
      weight: Yup.number(),
      quantity: Yup.number(),
    }),
  });

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

  useEffect(() => {
    let newVal = formik.values.weight;
    const mystring = formik.values.weight.toString().split(".").join("");
    if (formik.values.weight) {
      if (mystring.length <= 3) {
        if (mystring.length === 2) {
          newVal = mystring[0] + "." + mystring[1];
        }
        if (mystring.length === 3) {
          newVal = mystring[0] + "." + mystring[1] + mystring[2];
        }
      }
    }
    if (isNaN(Number.parseFloat(newVal))) {
      formik.setFieldValue("weight", "");
    } else {
      formik.setFieldValue("weight", Number.parseFloat(newVal));
    }
  }, [formik.values.weight]);

  let buyerType = "-";
  if (buyer.buyerType === "freezing") {
    buyerType = "انجماد";
  } else if (buyer.buyerType === "killer") {
    buyerType = "کشتارکن";
  } else if (buyer.buyerType === "killhouse") {
    buyerType = "کشتارگاه";
  }

  const reg = new RegExp(/^09\d{9}$/);

  return (
    <Grid container direction="column">
      <Grid>
        <Typography variant="h6" gutterBottom>
          اطلاعات خریدار
        </Typography>
        <Typography variant="subtitle1" gutterBottom>
          نام: {buyer.firstName} {buyer.lastName}
        </Typography>
        <Typography variant="subtitle1" gutterBottom>
          موبایل: {buyer.mobile}
        </Typography>
        <Typography variant="subtitle1" gutterBottom>
          شهر: {buyer.city}
        </Typography>
        <Typography variant="subtitle1" gutterBottom>
          استان: {buyer.province}
        </Typography>
        <Typography variant="subtitle1" gutterBottom>
          ماهیت خریدار: {buyerType}
        </Typography>
      </Grid>

      {provinceName !== "hamedan" && (
        <>
          <FormControl>
            <FormLabel id="demo-controlled-radio-buttons-group">
              پرداخت کننده
            </FormLabel>
            <RadioGroup
              row
              aria-labelledby="demo-controlled-radio-buttons-group"
              name="controlled-radio-buttons-group"
              value={payerValue}
              onChange={handleChangePayer}
            >
              <FormControlLabel
                value="poultry"
                control={<Radio />}
                label="مرغدار"
              />
              <FormControlLabel
                value="buyer"
                control={<Radio />}
                label="خریدار"
              />
            </RadioGroup>
          </FormControl>

          <Grid
            container
            xs={12}
            alignItems="center"
            justifyContent="center"
            mt={1}
            p={1}
            gap={1}
            style={{
              borderStyle: "solid",
              borderWidth: "2px",
              borderColor: "gray",
              borderRadius: "5px",
            }}
          >
            {payerValue === "poultry" ? (
              <Typography variant="body2" color="error">
                {!reg.test(item.poultry.user.mobile)
                  ? "فرمت تلفن مرغدار نادرست است! لطفا یک شماره موبایل معتبر وارد کنید."
                  : "از این قسمت میتوانید تلفن مرغدار را ویرایش کنید."}
              </Typography>
            ) : (
              <Typography variant="body2" color="error">
                {!reg.test(buyer.mobile)
                  ? "فرمت تلفن خریدار نادرست است! لطفا یک شماره موبایل معتبر وارد کنید."
                  : "از این قسمت میتوانید تلفن خریدار را ویرایش کنید."}
              </Typography>
            )}

            <TextField
              fullWidth
              id="mobile"
              value={formik.values.mobile}
              error={
                formik.touched.mobile ? Boolean(formik.errors.mobile) : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.mobile && Boolean(formik.errors.mobile)
                  ? formik.errors.mobile
                  : null
              }
              label="موبایل"
              autoComplete="current-password"
              variant="outlined"
            />
          </Grid>

          {isEdit && (
            <Grid container xs={12} gap={1} mt={2}>
              <Grid xs={12}>
                <TextField
                  id="quantity"
                  fullWidth
                  label="حجم (قطعه)"
                  variant="outlined"
                  sx={{ width: "100%" }}
                  value={formik.values.quantity}
                  error={
                    formik.touched.quantity
                      ? Boolean(formik.errors.quantity)
                      : null
                  }
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  helperText={
                    formik.touched.quantity && Boolean(formik.errors.quantity)
                      ? formik.errors.quantity
                      : null
                  }
                />
              </Grid>
              <Grid xs={12}>
                <TextField
                  id="weight"
                  fullWidth
                  label="میانگین وزن"
                  variant="outlined"
                  sx={{ width: "100%" }}
                  value={formik.values.weight}
                  error={
                    formik.touched.weight ? Boolean(formik.errors.weight) : null
                  }
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  helperText={
                    formik.touched.weight && Boolean(formik.errors.weight)
                      ? formik.errors.weight
                      : null
                  }
                />
              </Grid>
            </Grid>
          )}
        </>
      )}

      <Grid container gap={SPACING.TINY} mt={SPACING.SMALL}>
        {!isEdit && (
          <TextField
            label="یادداشت"
            variant="outlined"
            fullWidth
            multiline
            rows={4}
            value={value}
            onChange={handleChange}
          />
        )}
        {isEdit ? (
          <Button
            fullWidth
            variant="contained"
            color="primary"
            disabled={provinceName !== "hamedan" ? !formik.isValid : false}
            onClick={() => {
              dispatch(
                provinceEditFreeSaleService({
                  poultry_request_key: poultryRequestKey,
                  payer_type: payerValue,
                  buyer_mobile:
                    payerValue === "buyer" ? formik.values.mobile : null,
                  poultry_mobile:
                    payerValue === "poultry" ? formik.values.mobile : null,
                  Index_weight: formik.values.weight,
                  quantity: parseInt(formik.values.quantity),
                })
              ).then((r) => {
                if (r.payload.error) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: r.payload.error,
                    severity: "error",
                  });
                } else {
                  dispatch(
                    provinceGetFreeSalesRequestsService({
                      selectedDate1,
                      selectedDate2,
                    })
                  );
                  dispatch(
                    DRAWER({ right: false, bottom: false, content: null })
                  );
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "عملیات با موفقیت انجام شد.",
                    severity: "success",
                  });
                }
              });
            }}
          >
            ویرایش
          </Button>
        ) : (
          <>
            <Button
              style={{ flex: 0.5 }}
              variant="contained"
              color="success"
              disabled={provinceName !== "hamedan" ? !formik.isValid : false}
              onClick={() => {
                dispatch(
                  provinceCheckFreeSaleService({
                    poultry_request_key: poultryRequestKey,
                    state: "accepted",
                    message: value,
                    payer_type: payerValue,
                    buyer_mobile:
                      payerValue === "buyer" ? formik.values.mobile : null,
                    poultry_mobile:
                      payerValue === "poultry" ? formik.values.mobile : null,
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    dispatch(
                      provinceGetFreeSalesRequestsService({
                        selectedDate1,
                        selectedDate2,
                      })
                    );
                    dispatch(
                      DRAWER({ right: false, bottom: false, content: null })
                    );
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
              }}
            >
              تایید
            </Button>
            <Button
              style={{ flex: 0.5 }}
              variant="contained"
              color="error"
              onClick={() => {
                dispatch(
                  provinceCheckFreeSaleService({
                    poultry_request_key: poultryRequestKey,
                    state: "rejected",
                    message: value,
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    dispatch(
                      provinceGetFreeSalesRequestsService({
                        selectedDate1,
                        selectedDate2,
                      })
                    );
                    dispatch(
                      DRAWER({ right: false, bottom: false, content: null })
                    );
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
              }}
            >
              رد
            </Button>
          </>
        )}
      </Grid>
    </Grid>
  );
};
