import React, { useContext, useEffect } from "react";
import { TextField, Button } from "@mui/material";
import { useFormik } from "formik";
import * as Yup from "yup";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch } from "react-redux";
import {
  provincePolicyEditWeightRange,
  provincePolicySubmitWeightRange,
} from "../../services/province-policy-get-weight-range";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

function normalizeWeightInput(raw) {
  let v = String(raw).replace(/[^0-9.]/g, "");

  const firstDot = v.indexOf(".");
  if (firstDot !== -1) {
    v = v.slice(0, firstDot + 1) + v.slice(firstDot + 1).replace(/\./g, "");
  }

  if (v.length === 2 && !v.includes(".")) {
    v = `${v[0]}.${v[1]}`;
  }

  const parts = v.split(".");
  if (parts[0]?.length > 1) {
    const first = parts[0][0];
    const rest = parts[0]?.slice(1) + (parts[1] || "");
    v = rest ? `${first}.${rest.replace(/\D/g, "").slice(0, 1)}` : `${first}`;
  }

  if (v.includes(".")) {
    const [a, b = ""] = v.split(".");
    v = `${a}.${b.slice(0, 1)}`;
  }

  v = v.replace(/^0(\d)/, "$1");

  if (v === ".") v = "";

  const n = parseFloat(v);
  if (!Number.isNaN(n)) {
    if (n >= 10) v = "9.9";
    if (n < 0) v = "0";
  }

  return v;
}

const validationSchema = Yup.object({
  from_age: Yup.number()
    .required("این فیلد اجباری است!")
    .typeError("لطفا عدد وارد کنید!"),
  to_age: Yup.number()
    .required("این فیلد اجباری است!")
    .typeError("لطفا عدد وارد کنید!"),
  from_weight: Yup.string()
    .required("این فیلد اجباری است!")
    .test("is-weight", "Format: d.d and < 10", (val) => {
      if (val === undefined || val === null || val === "") return true;
      return /^\d(\.\d)?$/.test(String(val)) && parseFloat(val) < 10;
    }),
  to_weight: Yup.string()
    .required("این فیلد اجباری است!")
    .test("is-weight", "Format: d.d and < 10", (val, ctx) => {
      if (val === undefined || val === null || val === "") return true;
      const ok = /^\d(\.\d)?$/.test(String(val)) && parseFloat(val) < 10;
      if (!ok) return false;
      const fw = parseFloat(ctx.parent.from_weight);
      const tw = parseFloat(val);
      if (!Number.isNaN(fw) && !Number.isNaN(tw)) {
        return (
          tw >= fw ||
          ctx.createError({
            message: "حداکثر وزن از حداقل وزن باید بیشتر باشد!",
          })
        );
      }
      return true;
    }),
});

export const ProvincePolicyAddWeightRange = ({ item, fetchData }) => {
  const dispatch = useDispatch();

  const [openNotif] = useContext(AppContext);
  const formik = useFormik({
    initialValues: {
      from_age: item?.fromAge,
      to_age: item?.toAge,
      from_weight: item?.fromWeight,
      to_weight: item?.toWeight,
    },
    validationSchema,
    validateOnChange: true,
    validateOnBlur: true,
    onSubmit: (values) => {
      const payload = {
        from_age: Number(values.from_age),
        to_age: Number(values.to_age),
        from_weight:
          values.from_weight === "" ? null : Number(values.from_weight),
        to_weight: values.to_weight === "" ? null : Number(values.to_weight),
      };

      const service = item
        ? provincePolicyEditWeightRange
        : provincePolicySubmitWeightRange;
      dispatch(
        service({
          ...payload,
          ...(item ? { id: item?.id } : {}),
        })
      ).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());
          fetchData();
        }
      });
    },
  });

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

  const blockNonNumericKeys = (e) => {
    const blocked = ["e", "E", "+", "-", ","];
    if (blocked.includes(e.key)) e.preventDefault();
  };

  const handleWeightChange = (field) => (e) => {
    const next = normalizeWeightInput(e.target.value);
    formik.setFieldValue(field, next);
  };

  return (
    <Grid
      container
      xs={12}
      gap={2}
      justifyContent="center"
      alignItems="center"
      dierction="column"
    >
      <TextField
        fullWidth
        label="از سن"
        name="from_age"
        type="number"
        value={formik.values.from_age}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        inputProps={{
          step: 1,
          inputMode: "numeric",
          pattern: "[0-9]*",
          min: 0,
          max: 150,
        }}
        onKeyDown={blockNonNumericKeys}
        error={Boolean(formik.touched.from_age && formik.errors.from_age)}
        helperText={formik.touched.from_age && formik.errors.from_age}
      />

      <TextField
        fullWidth
        label="تا سن"
        name="to_age"
        type="number"
        value={formik.values.to_age}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        inputProps={{
          step: 1,
          inputMode: "numeric",
          pattern: "[0-9]*",
          min: 0,
          max: 150,
        }}
        onKeyDown={blockNonNumericKeys}
        error={Boolean(formik.touched.to_age && formik.errors.to_age)}
        helperText={formik.touched.to_age && formik.errors.to_age}
      />

      <TextField
        fullWidth
        label="از وزن"
        name="from_weight"
        value={formik.values.from_weight}
        onChange={handleWeightChange("from_weight")}
        onBlur={formik.handleBlur}
        inputProps={{ inputMode: "decimal" }}
        onKeyDown={blockNonNumericKeys}
        error={Boolean(formik.touched.from_weight && formik.errors.from_weight)}
        helperText={formik.touched.from_weight && formik.errors.from_weight}
      />

      <TextField
        fullWidth
        label="تا وزن"
        name="to_weight"
        value={formik.values.to_weight}
        onChange={handleWeightChange("to_weight")}
        onBlur={formik.handleBlur}
        inputProps={{ inputMode: "decimal" }}
        onKeyDown={blockNonNumericKeys}
        error={Boolean(formik.touched.to_weight && formik.errors.to_weight)}
        helperText={formik.touched.to_weight && formik.errors.to_weight}
      />

      <Button
        disabled={formik.values.to_age <= formik.values.from_age}
        fullWidth
        type="submit"
        variant="contained"
        onClick={formik.handleSubmit}
      >
        {item ? "ویرایش" : "ثبت"}
      </Button>
    </Grid>
  );
};
