import React, { useContext, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { IconButton, TextField, Typography, Box } from "@mui/material";
import CheckIcon from "@mui/icons-material/Check";
import EditIcon from "@mui/icons-material/Edit";
import { useFormik } from "formik";
import * as yup from "yup";
import { AppContext } from "../../../../contexts/AppContext";
import { useDispatch } from "react-redux";
import { provinceManageTradesEditPercents } from "../../services/province-manage-trades-edit-percents";
import {
  provinceManageGuildTradesEditAllPercents,
  provinceManageGuildTradesEditPercents,
} from "../../services/province-manage-guilds-trades-edit-percents";

const validationSchema = yup.object({
  commitmentPercent: yup
    .number()
    .min(0, "درصد نمی‌تواند کمتر از ۰ باشد")
    .max(100, "درصد نمی‌تواند بیشتر از ۱۰۰ باشد")
    .required("درصد تعهد الزامی است")
    .integer("درصد باید عدد صحیح باشد"),
});

export const ProvinceManageDistributionsSubmitCommitmentPercent = ({
  amount,
  updateTable,
  item,
  isGuild,
  isDashboard,
}) => {
  const [editMode, setEditMode] = useState(false);

  const [openNotif] = useContext(AppContext);

  const dispatch = useDispatch();

  const formik = useFormik({
    initialValues: {
      commitmentPercent: amount || 0,
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      const api = isDashboard
        ? provinceManageGuildTradesEditAllPercents
        : isGuild
        ? provinceManageGuildTradesEditPercents
        : provinceManageTradesEditPercents;
      dispatch(
        api({
          ...(isDashboard ? {} : { key: item?.key }),
          out_province_free_buying_commitment_percent:
            values?.commitmentPercent,
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          updateTable();
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });
      updateTable();
      setEditMode(false);
    },
  });

  const handleEditClick = () => {
    formik.setValues({ commitmentPercent: amount || 0 });
    formik.setErrors({});
    setEditMode(true);
  };

  return (
    <Grid xs={12} container justifyContent="center" alignItems="center">
      {editMode ? (
        <Box
          component="form"
          onSubmit={formik.handleSubmit}
          display="flex"
          alignItems="center"
          gap={1}
        >
          <TextField
            size="small"
            id="commitmentPercent"
            name="commitmentPercent"
            label="درصد تعهد"
            variant="outlined"
            type="number"
            value={formik.values.commitmentPercent}
            style={{ width: 80 }}
            inputProps={{
              min: 0,
              max: 100,
              step: 1,
            }}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.commitmentPercent &&
              Boolean(formik.errors.commitmentPercent)
            }
            helperText={
              formik.touched.commitmentPercent &&
              formik.errors.commitmentPercent
            }
          />
          <IconButton
            size="small"
            color="primary"
            type="submit"
            disabled={!formik.isValid || formik.isSubmitting}
          >
            <CheckIcon />
          </IconButton>
        </Box>
      ) : (
        <Box display="flex" alignItems="center">
          <Typography variant="caption">%{amount || 0}</Typography>
          <IconButton size="small" color="primary" onClick={handleEditClick}>
            <EditIcon />
          </IconButton>
        </Box>
      )}
    </Grid>
  );
};
