import React, { useContext, useEffect, useRef } from "react";
import { useFormik } from "formik";
import {
  Button,
  InputAdornment,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch } from "react-redux";
import { vetFarmCheckAllocation } from "../../services/vet-farm-check-allocation";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { vetFarmEditCodeAllocation } from "../../services/vet-farm-edit-code-allocation";
import PageviewIcon from "@mui/icons-material/Pageview";
import { Done } from "@mui/icons-material";
import { PropTypes } from "prop-types";
import { AppContext } from "../../../../contexts/AppContext";
import { format } from "date-fns";

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

  // Calculate if field should be locked/readonly
  const isLocked = item?.aggregateCode
    ? !item?.clearanceCode
    : getRoleFromUrl() === "ProvinceOperator" ||
      getRoleFromUrl() === "VetSupervisor" ||
      getRoleFromUrl() === "VetFarm" ||
      getRoleFromUrl() === "AdminX" ||
      getRoleFromUrl() === "SuperAdmin" ||
      getRoleFromUrl() === "Supporter"
    ? false
    : item.trash === true || item?.quarantineQuantity
    ? true
    : false;

  const formik = useFormik({
    initialValues: {
      name: "",
    },
    validate: (values) => {
      const errors = {};

      // Check if field is empty
      if (!values.name) {
        errors.name = "این فیلد اجباری است";
      }

      // Check if field contains at least one letter and one number
      const pattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]+$/;
      if (!pattern.test(values.name)) {
        errors.name = "باید شامل اعداد و حروف انگلیسی باشد";
      }

      return errors;
    },
  });

  useEffect(() => {
    if (formik.values.name) {
      formik.values.name = formik.values.name.toUpperCase();
    }
  }, [formik.values]);

  useEffect(() => {
    formik.setFieldValue("name", item?.clearanceCode || "");
  }, [item]);

  useEffect(() => {
    formik.validateForm();
  }, []);

  const handleSubmit = () => {
    if (item.clearanceCode) {
      dispatch(
        vetFarmEditCodeAllocation({
          kill_house_request_key: item.key,
          code: formik.values.name,
          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();
        }
      });
    } else {
      formik.setFieldValue("name", "");
      dispatch(
        vetFarmCheckAllocation({
          kill_house_request_key: item.key,
          code: formik.values.name,
          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();
        }
      });
    }
  };

  if (!isEditable) {
    return (
      <Typography variant="body2">
        {item?.clearanceCode ? item.clearanceCode : "-"}
      </Typography>
    );
  }

  return (
    <>
      <Grid
        container
        direction="row"
        alignItems="center"
        justifyContent="flex-start"
        gap={1}
        mt={1}
        sx={{ position: "relative" }}
      >
        <TextField
          id="name"
          size="small"
          variant="outlined"
          placeholder="کد قرنطینه"
          value={formik.values.name}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          error={formik.touched.name && Boolean(formik.errors.name)}
          helperText={
            formik.values.name && formik.touched.name && formik.errors.name
          }
          style={{ minWidth: "200px" }}
          sx={{
            "& .MuiOutlinedInput-root": {
              "& fieldset": {
                borderColor: "primary.main",
              },
              "&:hover fieldset": {
                borderColor: "primary.dark",
              },
              "&.Mui-focused fieldset": {
                borderColor: "primary.main",
              },
            },
          }}
          InputProps={{
            readOnly: isLocked ? true : false,
            startAdornment: (
              <InputAdornment position="start">
                {item.clearanceCode && (
                  <ViewCodeComponent clearanceCode={item.clearanceCode} />
                )}
              </InputAdornment>
            ),
          }}
        />
        {!isLocked && (
          <Button
            size="small"
            variant="contained"
            color="primary"
            onClick={handleSubmit}
            disabled={
              !formik.isValid || item.clearanceCode === formik.values.name
            }
            sx={{
              position: "absolute",
              right: "0",
              top: "0",
              minWidth: "40px",
              width: "40px",
              height: "39px",
            }}
          >
            <Done />
          </Button>
        )}
      </Grid>
      {item?.registerar?.date && (
        <Typography variant="caption" display="block">
          {`${format(new Date(item?.registerar?.date), "yyyy/MM/dd")} ${
            item?.registerar?.name
          }`}
        </Typography>
      )}
    </>
  );
};

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

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

VetFarmOperationRow.propTypes = {
  item: PropTypes.any,
  updateTable: PropTypes.any,
  isEditable: PropTypes.bool,
};
