import { useState, useRef, ReactNode, TouchEvent } from 'react';

interface SwipeableRowProps {
    children: ReactNode;
    onSwipeLeft?: () => void;
    onSwipeRight?: () => void;
    leftAction?: { icon: ReactNode; color: string; label: string };
    rightAction?: { icon: ReactNode; color: string; label: string };
    threshold?: number;
    disabled?: boolean;
}

export function SwipeableRow({
    children,
    onSwipeLeft,
    onSwipeRight,
    leftAction,
    rightAction,
    threshold = 80,
    disabled = false
}: SwipeableRowProps) {
    const [offset, setOffset] = useState(0);
    const [isSwiping, setIsSwiping] = useState(false);
    const startX = useRef(0);
    const startY = useRef(0);
    const isHorizontalSwipe = useRef<boolean | null>(null);

    const handleTouchStart = (e: TouchEvent) => {
        if (disabled) return;
        startX.current = e.touches[0].clientX;
        startY.current = e.touches[0].clientY;
        isHorizontalSwipe.current = null;
        setIsSwiping(true);
    };

    const handleTouchMove = (e: TouchEvent) => {
        if (!isSwiping || disabled) return;

        const currentX = e.touches[0].clientX;
        const currentY = e.touches[0].clientY;
        const diffX = currentX - startX.current;
        const diffY = currentY - startY.current;

        // Determine swipe direction on first significant movement
        if (isHorizontalSwipe.current === null) {
            if (Math.abs(diffX) > 10 || Math.abs(diffY) > 10) {
                isHorizontalSwipe.current = Math.abs(diffX) > Math.abs(diffY);
            }
        }

        // Only handle horizontal swipes
        if (!isHorizontalSwipe.current) return;

        // Limit swipe based on available actions
        let newOffset = diffX;
        if (!onSwipeRight && newOffset > 0) newOffset = 0;
        if (!onSwipeLeft && newOffset < 0) newOffset = 0;

        // Add resistance at edges
        const maxSwipe = threshold * 1.5;
        if (Math.abs(newOffset) > maxSwipe) {
            const excess = Math.abs(newOffset) - maxSwipe;
            const dampened = maxSwipe + excess * 0.2;
            newOffset = newOffset > 0 ? dampened : -dampened;
        }

        setOffset(newOffset);
    };

    const handleTouchEnd = () => {
        if (!isSwiping) return;
        setIsSwiping(false);

        if (Math.abs(offset) >= threshold) {
            if (offset > 0 && onSwipeRight) {
                // Animate to completion
                setOffset(150);
                setTimeout(() => {
                    onSwipeRight();
                    setOffset(0);
                }, 200);
                return;
            } else if (offset < 0 && onSwipeLeft) {
                setOffset(-150);
                setTimeout(() => {
                    onSwipeLeft();
                    setOffset(0);
                }, 200);
                return;
            }
        }

        // Snap back
        setOffset(0);
    };

    const progress = Math.min(Math.abs(offset) / threshold, 1);

    return (
        <div className="relative overflow-hidden rounded-xl">
            {/* Left action background (swipe right reveals this) */}
            {rightAction && offset > 0 && (
                <div
                    className={`absolute inset-y-0 left-0 flex items-center px-4 ${rightAction.color}`}
                    style={{ width: Math.abs(offset) }}
                >
                    <div
                        className="flex items-center gap-2 text-white font-medium"
                        style={{
                            opacity: progress,
                            transform: `scale(${0.8 + progress * 0.2})`
                        }}
                    >
                        {rightAction.icon}
                        {progress >= 1 && <span className="text-sm">{rightAction.label}</span>}
                    </div>
                </div>
            )}

            {/* Right action background (swipe left reveals this) */}
            {leftAction && offset < 0 && (
                <div
                    className={`absolute inset-y-0 right-0 flex items-center justify-end px-4 ${leftAction.color}`}
                    style={{ width: Math.abs(offset) }}
                >
                    <div
                        className="flex items-center gap-2 text-white font-medium"
                        style={{
                            opacity: progress,
                            transform: `scale(${0.8 + progress * 0.2})`
                        }}
                    >
                        {progress >= 1 && <span className="text-sm">{leftAction.label}</span>}
                        {leftAction.icon}
                    </div>
                </div>
            )}

            {/* Main content */}
            <div
                onTouchStart={handleTouchStart}
                onTouchMove={handleTouchMove}
                onTouchEnd={handleTouchEnd}
                style={{
                    transform: `translateX(${offset}px)`,
                    transition: isSwiping ? 'none' : 'transform 0.2s ease-out'
                }}
                className="relative bg-[var(--color-bg-elevated)]"
            >
                {children}
            </div>
        </div>
    );
}
