import { Button, IconButton, TextField, Typography } from "@mui/material";
import { useContext, useState } from "react";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { Grid } from "../../../../components/grid/Grid";
import EditIcon from "@mui/icons-material/Edit";
import { provinceChainsEditAllocation } from "../../services/province-chains-edit-allocation";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";

export const ChainBarManagementEditHealthCode = ({
  healthCode,
  item,
  updateTable,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const handleOpenModal = () => {
    dispatch(
      OPEN_MODAL({
        title: "ویرایش کد بهداشتی",
        size: "auto",
        content: (
          <EditHealthCodeModal
            initialValue={healthCode || ""}
            onSubmit={(newValue) => {
              dispatch(
                provinceChainsEditAllocation({
                  chain_allcation_key: item?.key,
                  health_code: newValue,
                })
              ).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",
                  });
                  updateTable();
                  dispatch(CLOSE_MODAL());
                }
              });
            }}
            onCancel={() => dispatch(CLOSE_MODAL())}
          />
        ),
      })
    );
  };

  return (
    <Grid
      container
      alignItems="center"
      gap={0.5}
      sx={{ width: "120px" }}
      justifyContent="center"
    >
      <Typography variant="caption">{healthCode || "-"}</Typography>
      <IconButton
        aria-label="edit"
        size="small"
        color="primary"
        onClick={handleOpenModal}
      >
        <EditIcon fontSize="small" />
      </IconButton>
    </Grid>
  );
};

const EditHealthCodeModal = ({ initialValue, onSubmit, onCancel }) => {
  const [value, setValue] = useState(initialValue);

  return (
    <Grid container direction="column" gap={2} minWidth={260}>
      <TextField
        label="کد بهداشتی"
        value={value}
        onChange={(event) => setValue(event.target.value)}
        fullWidth
        size="small"
      />
      <Grid container justifyContent="flex-end" xs={12} gap={1}>
        <Button
          variant="contained"
          color="primary"
          onClick={() => onSubmit(value)}
          style={{ flex: 1 }}
        >
          ثبت
        </Button>
        <Button
          style={{ flex: 1 }}
          variant="outlined"
          color="primary"
          onClick={onCancel}
        >
          لغو
        </Button>
      </Grid>
    </Grid>
  );
};
