import { type FC, Fragment, type ReactNode, useEffect } from 'react'
import { createPortal } from 'react-dom'
import HeaderModal from './HeaderModal'

interface Props {
    open: boolean,
    close: () => void,
    children: ReactNode,
    isHeader?: boolean,
    title_header?: string,
    width?: number
}

const DefaulModal: FC<Props> = (props: Props) => {

    useEffect(() => {
        if (props.open) {
            document.body.style.overflow = 'hidden'
        } else {
            document.body.style.overflow = 'auto'
        }
    }, [props.open])


    const modalContent = props.open ? (
        <Fragment>
            <div
                onClick={props.close}
                className='fixed size-full top-0 bottom-0 right-0 left-0 bg-black/40 inset-0 z-9998'
            />
            <div
                style={{ maxWidth: props.width }}
                className='xl:justify-center xl:items-center items-end flex overflow-x-hidden overflow-y-auto fixed inset-0 z-9999 h-auto top-0 bottom-0 m-auto outline-none focus:outline-none xl:max-w-xl mx-auto pointer-events-none'
            >
                <div
                    className='relative xl:h-full h-[80%] bottom-0 left-0 flex xl:items-center sm:h-auto w-full xl:my-6 xl:p-2 pointer-events-auto'
                    onClick={(e) => e.stopPropagation()}
                >
                    <div className='border-0 h-auto p-5 lg:min-w-full overflow-y-auto rounded-3xl rounded-b-none xl:rounded-b-3xl relative flex flex-col w-full bg-white outline-none focus:outline-none shadow-2xl'>


                        {
                            props.isHeader && props.title_header &&
                            <div className='pb-3 border-b border-border'>
                                <div className='h-[5px] w-[200px] mx-auto bg-[#D1D3D7] rounded-full mb-4 xl:hidden'></div>
                                <HeaderModal close={props.close} label={props.title_header} />
                            </div>
                        }

                        {props.children}


                    </div>
                </div>
            </div>
        </Fragment>
    ) : null

    return createPortal(modalContent, document.body)
}

export default DefaulModal