import React, { ReactNode, CSSProperties, useRef, useEffect } from 'react';

// components
import Typography from '../../Typography';
import CircularProgress from '../../CircularProgress';

// @ts-ignore
import CloseNew from '../../../../assets/images/modal-icons/close-new.svg'

// styles
import './styles.scss';

interface DialogProps {
  icon?: ReactNode;
  customStyles?: CSSProperties;
  open: boolean;
  handleClose: () => void;
  loading?: boolean;
  title?: string | ReactNode;
  subHeading?: string;
  description?: string;
  onSubmit?: () => void;
  onCancel?: () => void;
  cancelText?: string;
  submitText?: string;
  children?: ReactNode;
  isGallery?: boolean;
  currentTheme?: string | null | undefined;
  isQRCode?: boolean;
}

const buttonStyles: CSSProperties = {
  color: '#fff',
  backgroundColor: 'var(--primary-color)',
  maxWidth: '100%',
  minHeight: '50px',
  border: '0.5px solid var(--border-color)',
  fontSize: '14px',
  borderRadius: '8px'
};

const heading: CSSProperties = {
  color: '#000',
  fontWeight: '600',
  textAlign: 'center',
  margin: '0',
};

const subHeadingStyle: CSSProperties = {
  fontSize: '16px',
  color: '#656565',
  fontWeight: '400',
  textAlign: 'center',
  width: '100%',
  maxWidth: '400px',
  margin: '0',
  fontFamily: 'var(--font-family)',
  lineHeight: '20px',
};

const progressStyles: CSSProperties = {
  width: '20px',
  height: '20px',
  border: '2px solid #fff',
};

const DialogV2: React.FC<DialogProps> = ({
  icon = null,
  customStyles = {},
  open,
  handleClose,
  loading = false,
  title = "",
  subHeading = "",
  description = "",
  onSubmit,
  onCancel,
  cancelText = "",
  submitText = "",
  children = [],
  isGallery = false,
  currentTheme = "default",
  isQRCode = false
}) => {
  const contentAdjust = submitText.length > 6 ? "fit-content" : "100px";

  const modalRef = useRef<HTMLDivElement>(null);

  const handleClickOutside = (event: MouseEvent) => {
    if (modalRef.current && !modalRef.current.contains(event.target as Node)) {
      handleClose();
    }
  };

  const handleKeyDown = (event: KeyboardEvent) => {
    if (event.key === 'Escape' && !loading) {
      handleClose();
    }
  }

  useEffect(() => {
    if (open) {
      // document.addEventListener('mousedown', handleClickOutside);
      document.addEventListener('keydown', handleKeyDown);
    } else {
      // document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('keydown', handleKeyDown);
    }

    return () => {
      // document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [open]);

  useEffect(() => {
    const handleCopy = (event: KeyboardEvent) => {
      if ((event.metaKey || event.ctrlKey) && event.key === 'c') {
        event.stopPropagation();
      }
    };

    document.addEventListener('keydown', handleCopy, true);

    return () => {
      document.removeEventListener('keydown', handleCopy, true);
    };
  }, []);

  return (
    <>
      {
        isGallery || isQRCode ? (
          <div
            id="myModal"
            className={`modal-v2 ${isGallery && 'galleryModal'}`}
            style={{ display: open ? 'flex' : 'none' }}
          >
            <div className="modal-content" style={customStyles} ref={modalRef}>
              <div className="modal-header" style={{ paddingRight: !isQRCode ? '40px' : '0' }}>
                <Typography variant="p" style={{ ...heading, fontSize: "20px" }}>
                  {title}
                </Typography>
                <img src={CloseNew} alt="close" onClick={handleClose} />
              </div>
              <div className="modal-body">
                {icon && <div className="modal-icon">{icon}</div>}
                {subHeading && (
                  <Typography variant="p" style={subHeadingStyle}>
                    {subHeading}
                  </Typography>
                )}
                {description && (
                  <Typography
                    variant="p"
                    style={subHeadingStyle}
                  >
                    {description}
                  </Typography>
                )}
                {children}
                <div className="modal-footer">
                  {(!isGallery || isQRCode) &&
                    <>
                      <button onClick={onSubmit} disabled={loading}>
                        {loading ? <CircularProgress style={progressStyles} /> : submitText}
                      </button>
                      <button onClick={onCancel}>
                        {cancelText}
                      </button>
                    </>
                  }
                </div>
              </div>
            </div>
          </div>
        ) : (
          <div
            id="myModal"
            className={`confirm-modal-v2 ${isGallery && 'galleryModal'}`}
            style={{ display: open ? 'flex' : 'none' }}
          >
            <div className="confirm-modal-content" style={customStyles} ref={modalRef}>
              <div className="confirm-modal-header">
                {icon && <div className="confirm-modal-icon">{icon}</div>}
                <Typography variant="p" style={{ ...heading, fontSize: "24px", lineHeight: "24px" }}>
                  {title}
                </Typography>
                <img src={CloseNew} className="confirm-modal-close" alt="close" onClick={handleClose} />
              </div>
              <div className="confirm-modal-body">
                {subHeading && (
                  <Typography variant="p" style={subHeadingStyle}>
                    {subHeading}
                  </Typography>
                )}
                {description && (
                  <Typography
                    variant="p"
                    style={subHeadingStyle}
                  >
                    {description}
                  </Typography>
                )}
                {children}
                <div className="confirm-modal-footer">
                  {!isGallery &&
                    <>
                      <button onClick={onSubmit} disabled={loading}>
                        {loading ? <CircularProgress style={progressStyles} /> : submitText}
                      </button>
                      <button onClick={onCancel}>
                        {cancelText}
                      </button>
                    </>
                  }
                </div>
              </div>
            </div>
          </div>
        )
      }
    </>
  );
};

export default DialogV2;
