import {
  Button,
  IconButton,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useContext, useState, useEffect } from "react";
import { Grid } from "../../../../components/grid/Grid";
import EditIcon from "@mui/icons-material/Edit";
import AddCircleOutlineIcon from "@mui/icons-material/AddCircleOutline";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { vetFarmGetOutOfProvinceRequests } from "../../services/vet-farm-get-out-of-province-requests";
import { vetFarmEditOutOfProvinceDriverHealthCode } from "../../services/vet-farm-edit-out-of-province-driver-health-code";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";

export const VetFarmEditOutOfProvinceTrafficCode = ({ trafficCode, item }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [, , selectedDate1, , selectedDate2] = useContext(AppContext);

  const handleSubmit = (value) => {
    dispatch(
      vetFarmEditOutOfProvinceDriverHealthCode({
        poultry_request_key: item?.key,
        driver_health_code: value,
      })
    ).then((r) => {
      if (r.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "مشکلی پیش آمده است!",
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
        dispatch(
          vetFarmGetOutOfProvinceRequests({
            selectedDate1,
            selectedDate2,
          })
        );
        dispatch(CLOSE_MODAL());
      }
    });
  };

  const handleOpenModal = () => {
    dispatch(
      OPEN_MODAL({
        title: "ویرایش کد بهداشتی ماشین",
        size: "auto",
        content: (
          <OutOfProvinceTrafficCodeModal
            initialValue={trafficCode || ""}
            onSubmit={handleSubmit}
            onCancel={() => dispatch(CLOSE_MODAL())}
          />
        ),
      })
    );
  };

  return (
    <Grid container alignItems="center" justifyContent="center" gap={0.5}>
      {trafficCode ? (
        <Typography variant="caption">{trafficCode}</Typography>
      ) : null}
      <Tooltip
        title={trafficCode ? "ویرایش کد بهداشتی ماشین" : "ثبت کد بهداشتی ماشین"}
        placement="top"
      >
        <IconButton
          aria-label="edit"
          size="small"
          color="primary"
          onClick={handleOpenModal}
        >
          {trafficCode ? (
            <EditIcon fontSize="small" />
          ) : (
            <AddCircleOutlineIcon fontSize="small" />
          )}
        </IconButton>
      </Tooltip>
    </Grid>
  );
};

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

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

  const handleSave = () => {
    if (!value || value === initialValue) {
      return;
    }
    onSubmit(value);
  };

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