import { useScreenContext } from "@/src/contexts/ScreenContext";
import { Backdrop, Fade } from "@mui/material";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Modal from "@mui/material/Modal";
import React, { Fragment, useEffect, useState } from "react";
import { GrFormClose } from "react-icons/gr";
import { twMerge } from "tailwind-merge";

interface IOtherBtnProps {
  className: string;
  disabled: boolean;
  onClick: any;
  text: string;
}
interface ModalProps {
  children: React.ReactNode;
  opened?: boolean;
  onClose?: (arg?:any) => void;
  onDeny?: () => void | undefined;
  saved?: any;
  isSubmitting?: any;
  size?: Size;
  hasSaveButton?: boolean;
  hasDenyButton?: boolean;
  hasCloseBtn?: boolean;
  hasForm?: boolean;
  denyButtonText?: string;
  className?: string;
  classNameBody?: string;
  header?: string | any;
  typeButton?: string;
  defaultW?: string;
  otherButtons?: any;
}

type Size = "xs" | "sm" | "md" | "lg" | "xl" | undefined;

export default function ModalComponente({
  onClose,
  onDeny,
  opened = false,
  children,
  saved,
  size,
  header,
  hasCloseBtn = true,
  hasForm = true,
  typeButton = "button",
  hasSaveButton = true,
  hasDenyButton = false,
  denyButtonText,
  className,
  classNameBody = "px-8 py-6",
  defaultW = "w-96",
  isSubmitting = false,
  otherButtons,
  ...props
}: ModalProps) {
  let sizeModal = "";
  const [openModal, setOpenModal] = useState(false);
  useEffect(() => {
    setOpenModal(opened);
  }, [opened]);
  switch (size) {
    case "xs":
      sizeModal = "w-48";
      break;
    case "sm":
      sizeModal = "w-95";
      break;
    case "md":
      sizeModal = "w-130";
      break;
    case "lg":
      sizeModal = "w-230";
      break;
    case "xl":
      sizeModal = "w-[1200px]";
      break;
    default:
      sizeModal = defaultW; // Deixei esse como default, mas pode ser alterado
      break;
  }

  const claasBoxModal = twMerge(
    `absolute dark:bg-black bg-white  ${
      // "w-[90%] sm:w-[80%]"
      sizeModal != "w-96" ? sizeModal : "w-[90%] sm:w-[80%]"
    }  top-1/2 left-1/2 max-h-[90%]   overflow-y-auto -translate-x-2/4 -translate-y-2/4  rounded-md`,
    className
  );

  const getBackgroundColorFromClassName = (className: any) => {
    const colorClassRegex = /bg-(\w+)/;
    const colorDarkRegex = /dark:bg-(\w+)/;

    const match = className?.match(colorClassRegex);
    const darkMatch = className?.match(colorDarkRegex);

    const retorno = [];
    if (match) retorno.push(match[0]);

    if (darkMatch) retorno.push(darkMatch[0]);

    return retorno.join(" ") || "bg-white dark:bg-black";
  };
  const { isMobile } = useScreenContext();

  return (
    <Fragment>
      <Modal
        {...props}
        style={{ zIndex: 40, zoom: isMobile ? 1 : 0.8 }}
        open={openModal}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
        slots={{ backdrop: Backdrop }}
        slotProps={{
          backdrop: {
            timeout: 500,
          },
        }}
        className="transition-all"
      >
        <Fade in={openModal}>
          <Box className={claasBoxModal}>
            <header
              className={`sticky z-99999 text-black dark:text-stroke font-medium text-lg overflow-y-auto w-full flex  justify-between top-0 right-0 dark:bg-black ${getBackgroundColorFromClassName(className)}`}
            >
              {header ? (
                <div className="p-2 pl-5 w-full">{header}</div>
              ) : (
                <div></div>
              )}
              {hasCloseBtn && (
                <Button onClick={onClose}>
                  <GrFormClose size={20} />
                </Button>
              )}
            </header>
            {/* <hr /> */}

            <main className={classNameBody}>
              {hasForm ? (
                <form className="">{children}</form>
              ) : (
                <div className="">{children}</div>
              )}
            </main>

            {(hasDenyButton || hasSaveButton || otherButtons) && (
              <footer
                className={`bottom-2 ${(hasDenyButton || hasSaveButton || otherButtons) && "mt-3"}  sticky w-full flex justify-end gap-2 pr-3 bg-white dark:bg-black`}
              >
                {hasDenyButton && (
                  <button
                    className={`bg-body  ${
                      isSubmitting && "opacity-50 pointer-events-none" // Disable button if submitting
                    } text-white rounded-md text-sm py-2 px-4`}
                    onClick={onDeny}
                    type="button"
                  >
                    {denyButtonText}
                  </button>
                )}
                {hasSaveButton && (
                  <button
                    className={`bg-success text-white rounded-md text-sm py-2 px-4 ${
                      isSubmitting && "opacity-50 pointer-events-none" // Disable button if submitting
                    }`}
                    type="submit"
                    disabled={isSubmitting}
                    onClick={saved}
                  >
                    Confirmar
                  </button>
                )}
                {otherButtons &&
                  otherButtons.map((button: IOtherBtnProps, index: number) => {
                    return (
                      <button
                        key={index}
                        className={button.className}
                        disabled={button.disabled}
                        onClick={button.onClick}
                      >
                        {button.text}
                      </button>
                    );
                  })}
              </footer>
            )}
          </Box>
        </Fade>
      </Modal>
    </Fragment>
  );
}
