import { ReactNode, useEffect, useRef, useState, TouchEvent } from 'react';
import { X } from 'lucide-react';

interface BottomSheetProps {
    isOpen: boolean;
    onClose: () => void;
    title?: string;
    children: ReactNode;
    height?: 'auto' | 'half' | 'full';
}

export function BottomSheet({ isOpen, onClose, title, children, height = 'auto' }: BottomSheetProps) {
    const [isClosing, setIsClosing] = useState(false);
    const [dragOffset, setDragOffset] = useState(0);
    const startY = useRef(0);
    const sheetRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (isOpen) {
            document.body.style.overflow = 'hidden';
            setIsClosing(false);
            setDragOffset(0);
        } else {
            document.body.style.overflow = '';
        }
        return () => {
            document.body.style.overflow = '';
        };
    }, [isOpen]);

    const handleClose = () => {
        setIsClosing(true);
        setTimeout(() => {
            onClose();
            setIsClosing(false);
        }, 200);
    };

    const handleTouchStart = (e: TouchEvent) => {
        startY.current = e.touches[0].clientY;
    };

    const handleTouchMove = (e: TouchEvent) => {
        const currentY = e.touches[0].clientY;
        const diff = currentY - startY.current;

        // Only allow dragging down
        if (diff > 0) {
            setDragOffset(diff);
        }
    };

    const handleTouchEnd = () => {
        if (dragOffset > 100) {
            handleClose();
        }
        setDragOffset(0);
    };

    if (!isOpen) return null;

    const heightClasses = {
        auto: 'max-h-[85vh]',
        half: 'h-[50vh]',
        full: 'h-[90vh]'
    };

    return (
        <div className="fixed inset-0 z-[100] md:hidden">
            {/* Backdrop */}
            <div
                className={`absolute inset-0 bg-black transition-opacity duration-200 ${isClosing ? 'opacity-0' : 'opacity-50'}`}
                onClick={handleClose}
            />

            {/* Sheet */}
            <div
                ref={sheetRef}
                className={`absolute bottom-0 left-0 right-0 bg-[var(--color-bg-elevated)] rounded-t-2xl shadow-xl transition-transform duration-200 ${heightClasses[height]} ${isClosing ? 'translate-y-full' : 'translate-y-0'}`}
                style={{ transform: isClosing ? 'translateY(100%)' : `translateY(${dragOffset}px)` }}
            >
                {/* Drag Handle */}
                <div
                    className="flex justify-center py-3 cursor-grab active:cursor-grabbing"
                    onTouchStart={handleTouchStart}
                    onTouchMove={handleTouchMove}
                    onTouchEnd={handleTouchEnd}
                >
                    <div className="w-10 h-1 bg-slate-300 dark:bg-slate-600 rounded-full" />
                </div>

                {/* Header */}
                {title && (
                    <div className="flex items-center justify-between px-4 pb-4 border-b border-[var(--color-border-default)]">
                        <h3 className="text-lg font-bold text-[var(--color-text-primary)]">{title}</h3>
                        <button
                            onClick={handleClose}
                            className="p-2 rounded-full hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors"
                        >
                            <X size={20} className="text-[var(--color-text-tertiary)]" />
                        </button>
                    </div>
                )}

                {/* Content */}
                <div className={`overflow-y-auto ${title ? '' : 'pt-0'}`} style={{ maxHeight: 'calc(85vh - 80px)' }}>
                    {children}
                </div>
            </div>
        </div>
    );
}

// Desktop modal fallback wrapper
interface ResponsiveModalProps {
    isOpen: boolean;
    onClose: () => void;
    title?: string;
    children: ReactNode;
    className?: string;
}

export function ResponsiveModal({ isOpen, onClose, title, children, className = '' }: ResponsiveModalProps) {
    if (!isOpen) return null;

    return (
        <>
            {/* Desktop Modal */}
            <div className="hidden md:flex fixed inset-0 z-[100] items-center justify-center p-4">
                <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={onClose} />
                <div className={`relative bg-[var(--color-bg-elevated)] rounded-2xl shadow-2xl max-w-lg w-full max-h-[85vh] overflow-hidden animate-scale-in ${className}`}>
                    {title && (
                        <div className="flex items-center justify-between p-4 border-b border-[var(--color-border-default)]">
                            <h3 className="text-lg font-bold text-[var(--color-text-primary)]">{title}</h3>
                            <button
                                onClick={onClose}
                                className="p-2 rounded-full hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors"
                            >
                                <X size={20} className="text-[var(--color-text-tertiary)]" />
                            </button>
                        </div>
                    )}
                    <div className="overflow-y-auto" style={{ maxHeight: 'calc(85vh - 60px)' }}>
                        {children}
                    </div>
                </div>
            </div>

            {/* Mobile Bottom Sheet */}
            <BottomSheet isOpen={isOpen} onClose={onClose} title={title}>
                {children}
            </BottomSheet>
        </>
    );
}
