'use client';

import React, { useRef } from 'react'
import BlurredOverlayContainer, { BlurredOverlayContainerProps } from '../overlays/BlurredOverlayContainer'
import clsx from 'clsx'
import CloseIcon from '../icons/CloseIcon'
import { motion, PanInfo, Variants } from 'framer-motion'

type Props = {
    title?: string,
    showCloseButton?: boolean,
    showTitle?: boolean,
    blurOpacity?: string | number | null,
    overrideClassName?: string,
    titlePadding?: string,
} & BlurredOverlayContainerProps

const AnimatedBottomSheet = ({ blurOpacity = 64, overrideClassName = '', showTitle = true, showCloseButton = true, titlePadding = 'ps-[31px] pe-[33px]', ...props }: Props) => {
    const closeRef: React.Ref<HTMLDivElement> | undefined = useRef(null);

    const variants: Variants = {
        hidden: {
            y: '100%',
        },
        visible: {
            y: 0,
            transition: {
                duration: 0.1,
                ease: 'easeInOut',
            },
        },
    };

    const onDrag = (_event: MouseEvent | TouchEvent | PointerEvent, info: PanInfo) => {
        if (info.offset.y > 200) {
            if (closeRef.current) {
                closeRef.current.click();
            }
        }
    }

    return (
        <BlurredOverlayContainer {...props} outDelay={100}>
            <motion.div
                drag='y'
                dragConstraints={{ top: 0, bottom: 0 }}
                transition={{ type: "spring", stiffness: 200, damping: 20 }}
                dragTransition={{ bounceDamping: 10, bounceStiffness: 600 }}
                dragElastic={0.05}
                onDragEnd={onDrag}
                data-visible={props.visible}
                data-bg-opacity={blurOpacity}
                className={clsx(
                    overrideClassName ?? '',
                    'absolute left-0 w-full rounded-t-4xl pt-[39px] pb-6',
                    'bottom-0',
                    'bg-container/64 dark:bg-container/80'
                )}
                initial="hidden"
                animate={props.visible ? 'visible' : 'hidden'}
                variants={variants}
            >
                <div className={clsx(titlePadding, 'flex justify-between')}>
                    {showTitle &&
                        <div className='text-lg font-medium text-foreground leading-8 mt-2.5'>
                            {props.title}
                        </div>
                    }
                    {showCloseButton &&
                        <div ref={closeRef} onClick={props.onClick} className="bg-container/38 w-8 h-8 rounded-full p-1.5">
                            <CloseIcon size={20} />
                        </div>
                    }
                </div>
                {props.children}
            </motion.div>

        </BlurredOverlayContainer>
    )
}

export default AnimatedBottomSheet
