import {
  Button,
  IconButton,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { Edit } from "@mui/icons-material";
import { useDispatch } from "react-redux";
import { vetFarmEditTrafficCodeService } from "../../services/vet-farm-edit-traffic-code";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";

export const VetFarmEditTrafficCode = ({
  trafficCode,
  killHouseRequestKey,
  updateTable,
  isEditable = true,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  if (!isEditable) {
    return (
      <Typography
        variant="body2"
        sx={{ display: "flex", alignItems: "center" }}
      >
        {trafficCode || "-"}
      </Typography>
    );
  }

  const handleOpenModal = () => {
    dispatch(
      OPEN_MODAL({
        title: "ویرایش کد حمل و نقل",
        size: "auto",
        content: (
          <TrafficCodeModal
            initialValue={trafficCode || ""}
            onSubmit={(newCode) => {
              dispatch(
                vetFarmEditTrafficCodeService({
                  key: killHouseRequestKey,
                  traffic_code: newCode,
                  role: getRoleFromUrl(),
                })
              ).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"
      justifyContent="center"
      gap={0.5}
      sx={{
        width: "140px",
      }}
    >
      <Typography variant="body2">{trafficCode || "-"}</Typography>
      <Tooltip title="ویرایش کد حمل و نقل" placement="top">
        <IconButton
          size="small"
          color="primary"
          aria-label="edit"
          onClick={handleOpenModal}
        >
          <Edit fontSize="small" />
        </IconButton>
      </Tooltip>
    </Grid>
  );
};

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

  useEffect(() => {
    setValue(initialValue);
  }, [initialValue]);

  const handleSubmit = () => {
    if (!value) {
      return;
    }
    onSubmit(value);
  };

  return (
    <Grid container direction="column" gap={2} minWidth={260}>
      <TextField
        variant="outlined"
        value={value}
        size="small"
        placeholder="کد حمل و نقل"
        onChange={(event) => setValue(event.target.value)}
        inputProps={{
          inputMode: "numeric",
          pattern: "[0-9]*",
        }}
        fullWidth
      />
      <Grid container justifyContent="flex-end" gap={1} xs={12}>
        <Button
          size="small"
          variant="contained"
          color="primary"
          onClick={handleSubmit}
          disabled={!value || value === initialValue}
          sx={{
            flex: 1,
          }}
        >
          ثبت
        </Button>
        <Button
          size="small"
          variant="outlined"
          color="primary"
          onClick={onCancel}
          sx={{
            flex: 1,
          }}
        >
          لغو
        </Button>
      </Grid>
    </Grid>
  );
};
