import React, { useContext, useEffect, useRef, useState } from "react";
import {
  Button,
  Grid,
  IconButton,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useDispatch } from "react-redux";
import PageviewIcon from "@mui/icons-material/Pageview";
import EditIcon from "@mui/icons-material/Edit";
import AddCircleOutlineIcon from "@mui/icons-material/AddCircleOutline";
import { PropTypes } from "prop-types";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { provinceChainsEditBar } from "../../services/province-chains-edit-bar";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";

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

  const handleOpenModal = () => {
    dispatch(
      OPEN_MODAL({
        title: "ثبت کد قرنطینه",
        size: "auto",
        content: (
          <SubmitQuarantineModal
            code={item.quarantineCode || ""}
            isLocked={isLocked}
            onSubmit={(newCode) => {
              dispatch(
                provinceChainsEditBar({
                  chain_allcation_key: item.key,
                  quarantine_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"
      gap={0.5}
      sx={{
        width: item.quarantineCode ? "160px" : "auto",
        justifyContent: "center",
      }}
    >
      {item.quarantineCode ? (
        <ViewCodeComponent clearanceCode={item.quarantineCode} />
      ) : (
        <IconButton
          aria-label="add"
          size="small"
          color="primary"
          onClick={handleOpenModal}
        >
          <AddCircleOutlineIcon fontSize="small" />
        </IconButton>
      )}
      {!isLocked && (
        <IconButton
          aria-label="edit"
          size="small"
          color="primary"
          onClick={handleOpenModal}
          sx={{ display: item.quarantineCode ? "inline-flex" : "none" }}
        >
          <EditIcon fontSize="small" />
        </IconButton>
      )}
    </Grid>
  );
};

const ViewCodeComponent = ({ clearanceCode }) => {
  const formRef = useRef(null);

  const handleImageClick = () => {
    if (formRef.current) {
      formRef.current.submit();
    }
  };
  return (
    <Grid
      container
      alignItems="center"
      justifyContent="center"
      gap={0.5}
      style={{ width: "auto" }}
    >
      <Tooltip title="مشاهده گواهینامه" arrow>
        <form
          action="https://e.ivo.ir/Rahgiri/Gidprnt.aspx"
          method="post"
          target="_blank"
          ref={formRef}
          style={{
            cursor: "pointer",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <input name="gid" type="hidden" value={clearanceCode} />

          <PageviewIcon color="primary" onClick={handleImageClick} />
        </form>
      </Tooltip>
      <Typography variant="caption" color="primary">
        {clearanceCode}
      </Typography>
    </Grid>
  );
};

const SubmitQuarantineModal = ({ code, isLocked, onSubmit, onCancel }) => {
  const [value, setValue] = useState(code);
  const [error, setError] = useState("");

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

  const validate = (val) => {
    if (!val) {
      setError("این فیلد اجباری است");
      return false;
    }
    const pattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]+$/;
    if (!pattern.test(val)) {
      setError("باید شامل اعداد و حروف انگلیسی باشد");
      return false;
    }
    setError("");
    return true;
  };

  const handleChange = (event) => {
    const newValue = event.target.value.toUpperCase();
    setValue(newValue);
    validate(newValue);
  };

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

  return (
    <Grid container direction="column" gap={2}>
      <TextField
        label="کد قرنطینه"
        value={value}
        onChange={handleChange}
        size="small"
        fullWidth
        error={Boolean(error)}
        helperText={error}
        InputProps={{
          readOnly: isLocked,
        }}
      />
      <Grid container justifyContent="flex-end" gap={1} xs={12}>
        <Button
          variant="contained"
          color="primary"
          onClick={handleSubmit}
          disabled={isLocked}
          style={{ flex: 1 }}
        >
          ثبت
        </Button>
        <Button
          style={{ flex: 1 }}
          variant="outlined"
          color="primary"
          onClick={onCancel}
        >
          لغو
        </Button>
      </Grid>
    </Grid>
  );
};

ChainSubmitQuarantineCode.propTypes = {
  item: PropTypes.any,
  updateTable: PropTypes.any,
  isLocked: PropTypes.any,
};
