import { TextField } from "@mui/material";
import { useFormik } from "formik";
import { useEffect } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { Yup } from "../../../../lib/yup/yup";

const validationSchema = Yup.object({
  percent: Yup.number()
    .typeError("لطفا عدد وارد کنید")
    .min(0, "باید برابر یا بزرگتر از 0 باشد")
    .max(100, "باید کوچکتر یا برابر با 100 باشد")
    .required("درصد الزامی است"),
});

export const ProvinceManageSlaughterhouseQuota = ({
  percent,
  slaughterKey,
  onPercentChange,
}) => {
  const formik = useFormik({
    initialValues: {
      percent: percent,
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      // console.log(values);
    },
  });

  useEffect(() => {
    formik.setFieldValue("percent", percent);
  }, [percent]);

  return (
    <Grid container justifyContent="center">
      <TextField
        size="small"
        name="percent"
        type={"number"}
        className="percent-input-quota"
        value={formik.values.percent}
        onChange={(e) => {
          onPercentChange(slaughterKey, Number(e.target.value));
          formik.setFieldValue("percent", e.target.value);
        }}
        onBlur={formik.handleBlur}
        error={formik.touched.percent && Boolean(formik.errors.percent)}
        helperText={formik.touched.percent && formik.errors.percent}
        InputProps={{
          startAdornment: <span>%</span>,
        }}
        inputProps={{ step: 0.1 }}
        style={{ width: 100, textAlign: "center" }}
      />
    </Grid>
  );
};
