import React, { useState, useRef } from "react";
import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Grid,
  IconButton,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
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 { editBarClearanceBar } from "../../features/slaughter-house/services/edit_bar_clearance_code";
import { AppContext } from "../../contexts/AppContext";
import { useDispatch } from "react-redux";
import { Yup } from "../../lib/yup/yup";
import { useFormik } from "formik";

export const CheckCleanceCode = ({
  clearanceCode,
  onSave,
  bar_key,
  register_type,
}) => {
  const dispatch = useDispatch();
  const { openNotif } = React.useContext(AppContext);
  const [isEditing, setIsEditing] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const inputRef = useRef(null);

  const formik = useFormik({
    initialValues: {
      clearanceCode: clearanceCode || "",
    },
    validationSchema: Yup.object({
      clearanceCode: Yup.string()
        .required("این فیلد اجباری است!")
        .matches(/^[A-Z0-9]+$/, "فقط حروف بزرگ و عدد مجاز است!"),
    }),

    onSubmit: async (values) => {
      setIsSaving(true);

      try {
        const result = await dispatch(
          editBarClearanceBar({
            key: bar_key,
            bar_clearance_code: values.clearanceCode,
          })
        );

        if (result.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: result.error.message || "خطا در ذخیره سازی",
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "کد با موفقیت ذخیره شد",
            severity: "success",
          });
          if (onSave) onSave(values.clearanceCode);
          setIsEditing(false);
        }
      } catch (error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "خطا در ارتباط با سرور",
          severity: "error",
        });
      } finally {
        setIsSaving(false);
      }
    },
  });

  const handleOpenModal = () => {
    setIsEditing(true);
  };

  const canEdit = register_type === "manual";

  return (
    <Grid
      container
      alignItems="center"
      justifyContent="center"
      gap={0.5}
      style={{
        width: canEdit ? "160px" : "auto",
      }}
    >
      {formik.values.clearanceCode ? (
        <ViewCodeComponent clearanceCode={formik.values.clearanceCode} />
      ) : null}
      {canEdit && (
        <Tooltip
          title={
            formik.values.clearanceCode ? "ویرایش کد گواهی" : "ثبت کد گواهی"
          }
          placement="top"
        >
          <IconButton size="small" color="primary" onClick={handleOpenModal}>
            {formik.values.clearanceCode ? (
              <EditIcon fontSize="small" />
            ) : (
              <AddCircleOutlineIcon fontSize="small" />
            )}
          </IconButton>
        </Tooltip>
      )}
      {isEditing && (
        <Dialog
          open={isEditing}
          onClose={() => {
            formik.resetForm();
            setIsEditing(false);
          }}
        >
          <DialogTitle>ویرایش کد گواهی</DialogTitle>
          <DialogContent>
            <TextField
              inputRef={inputRef}
              name="clearanceCode"
              value={formik.values.clearanceCode}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              error={
                formik.touched.clearanceCode &&
                Boolean(formik.errors.clearanceCode)
              }
              helperText={
                formik.touched.clearanceCode && formik.errors.clearanceCode
              }
              size="small"
              fullWidth
              autoFocus
            />
          </DialogContent>
          <DialogActions>
            <Button
              onClick={() => {
                formik.resetForm();
                setIsEditing(false);
              }}
              color="primary"
            >
              لغو
            </Button>
            <Button
              onClick={() => {
                formik.handleSubmit();
                setIsEditing(false);
              }}
              color="primary"
              disabled={isSaving || !formik.dirty}
            >
              ذخیره
            </Button>
          </DialogActions>
        </Dialog>
      )}
    </Grid>
  );
};

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

  const handleImageClick = () => {
    if (formRef.current) {
      formRef.current.submit();
    }
  };
  return (
    <Grid
      container
      style={{ width: "auto" }}
      alignItems="center"
      justifyContent="center"
      gap={0.5}
    >
      <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>
  );
};

CheckCleanceCode.propTypes = {
  clearanceCode: PropTypes.any,
  onSave: PropTypes.func,
  bar_key: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  register_type: PropTypes.string,
};

ViewCodeComponent.propTypes = {
  clearanceCode: PropTypes.any,
};
