// @ts-nocheck
import React, { ReactNode, useEffect, useRef } from 'react'
import styled from 'styled-components'

export type ModalProps = {
 /**
   * modal status
   */
  show: boolean;
  /**
   * elements inside the modal
   */
  children?: ReactNode;
  /**
   * change the modal status
   */
  setShow: (show:boolean) => void;
  css?: string;
};

export const Modal = ({ children,show,setShow,css }: ModalProps):JSX.Element => {

  const ref = useRef<HTMLDivElement>(null)

  const handleClick = (e:React.MouseEvent<HTMLElement>)=>{
    if(ref.current !== e.target) return
    setShow(false)
  }

  useEffect(()=>{
    const listener = (e:React.KeyboardEvent)=>{
      if(e.key==='Escape') setShow(false)
    }
    window.addEventListener('keyup',listener)
    return ()=>window.removeEventListener('keyup',listener)
  })


  return (
    <>
      {show && (
        <ModalBackground ref={ref} css={css} onClick={handleClick}>
          <ModalContainer>
            {children}
          </ModalContainer>
        </ModalBackground>
      )}
    </>
  )
}

const ModalBackground = styled.div<{css?:string}>`
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.4);
  position: fixed;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1;
    
  ${(p) => p.css}  
`

const ModalContainer = styled.div`
  width: fit-content;
  height: fit-content;
  border-radius: 12px;
  background-color: white;
  box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
  display: flex;
  flex-direction: column;
  padding: 20px;
`