import React, { useRef, useEffect, useState } from 'react';
import { View, Text, StyleSheet, Animated, Image, PanResponder, Vibration, Dimensions } from 'react-native';

interface SliderProps {
    lockStatus?: number;
    onStatusChange?: (status: boolean) => void;
}

const { width: SCREEN_WIDTH } = Dimensions.get('window');
const rpx = (px: number) => {
    return (SCREEN_WIDTH / 750) * px;
};

const Slider: React.FC<SliderProps> = ({ lockStatus = 1, onStatusChange }) => {
    // 修改初始值逻辑：lockStatus = 0（关锁）时滑块在左侧，lockStatus = 1（开锁）时滑块在右侧
    const translateX = useRef(new Animated.Value(lockStatus === 0 ? 0 : rpx(180))).current;
    const maxWidth = rpx(180);
    const buttonWidth = rpx(86);
    // 修改状态判断：lockStatus = 1 表示开锁（isRight = true）
    const [isRight, setIsRight] = useState(lockStatus === 1);
    const hasVibratedRef = useRef(false);
    const offsetRef = useRef(0);

    useEffect(() => {
        const id = translateX.addListener(({ value }) => {
            if (value >= maxWidth * 0.95) {
                setIsRight(true);
            } else if (value <= maxWidth * 0.05) {
                setIsRight(false);
            }
        });

        return () => translateX.removeListener(id);
    }, []);

    const iconOpacity = translateX.interpolate({
        inputRange: [maxWidth * 0.9, maxWidth],
        outputRange: [1, 0],
        extrapolate: 'clamp'
    });

    const backgroundWidth = translateX.interpolate({
        inputRange: [0, maxWidth],
        outputRange: [buttonWidth - rpx(2), maxWidth + buttonWidth - rpx(2)],
        extrapolate: 'clamp'
    });

    const panResponder = useRef(
        PanResponder.create({
            onStartShouldSetPanResponder: () => true,
            onMoveShouldSetPanResponder: () => true,
            onPanResponderGrant: () => {
                hasVibratedRef.current = false;
                offsetRef.current = translateX._value;
            },
            onPanResponderMove: (_, gestureState) => {
                let newValue = offsetRef.current + gestureState.dx;
                newValue = Math.max(0, Math.min(maxWidth, newValue));
                translateX.setValue(newValue);

                if (!hasVibratedRef.current) {
                    if (newValue >= maxWidth * 0.95 || newValue <= maxWidth * 0.05) {
                        Vibration.vibrate(20);
                        hasVibratedRef.current = true;
                    }
                }
            },
            onPanResponderRelease: (_, gestureState) => {
                const currentValue = translateX._value;
                let toValue;
                let finalIsRight;
                
                if (isRight) {
                    if (gestureState.dx < -maxWidth / 4) {
                        toValue = 0;
                        finalIsRight = false;
                    } else {
                        toValue = maxWidth;
                        finalIsRight = true;
                    }
                } else {
                    if (gestureState.dx > maxWidth / 4) {
                        toValue = maxWidth;
                        finalIsRight = true;
                    } else {
                        toValue = 0;
                        finalIsRight = false;
                    }
                }

                Animated.timing(translateX, {
                    toValue,
                    duration: 100,
                    useNativeDriver: false,
                }).start(() => {
                    hasVibratedRef.current = false;
                    console.log('Slider 状态改变:', {
                        finalIsRight,
                        当前状态: finalIsRight ? '开锁' : '关锁'
                    });
                    if (onStatusChange) {
                        onStatusChange(finalIsRight);
                    }
                });
            },
        })
    ).current;

    return (
        <View style={styles.container}>
            <View style={styles.car_Opne_box}>
                <View style={styles.defaultBackground} />
                
                <Animated.View
                    style={[
                        styles.background,
                        {
                            width: backgroundWidth,
                        }
                    ]}
                />

                <Animated.View
                    {...panResponder.panHandlers}
                    style={[
                        styles.imageContainer,
                        {
                            transform: [{ translateX }]
                        }
                    ]}
                >
                    <Image
                        source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uY9tYXXZztuE1VTLDl5y' }}
                        style={styles.imageContent}
                        resizeMode="contain"
                    />
                </Animated.View>

                <Animated.Image
                    source={{ uri: 'https://lxnapi.ccttiot.com/bike/img/static/uEJob4XbADaL9ohOTVTL' }}
                    style={[
                        styles.icon,
                        { opacity: iconOpacity }
                    ]}
                    resizeMode="contain"
                />
            </View>
            <Text style={styles.text}>
                {isRight ? '左滑关闭' : '右滑启动'}
            </Text>
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    car_Opne_box: {
        justifyContent: 'center',
        width: rpx(268),
        height: rpx(90),
        position: 'relative',
        borderRadius: rpx(45),
        overflow: 'hidden',
    },
    background: {
        position: 'absolute',
        left: 0,
        top: 0,
        height: '100%',
        backgroundColor: '#4297F3',
        borderRadius: rpx(45),
        zIndex: 1,
    },
    defaultBackground: {
        position: 'absolute',
        left: 0,
        top: 0,
        width: '100%',
        height: '100%',
        backgroundColor: '#EBEBEB',
        borderRadius: rpx(45),
        zIndex: 0,
    },
    imageContainer: {
        width: rpx(86),
        height: rpx(86),
        position: 'absolute',
        top: '50%',
        left: 0,
        marginTop: -rpx(43),
        zIndex: 3,
    },
    imageContent: {
        width: '100%',
        height: '100%',
    },
    icon: {
        width: rpx(32),
        height: rpx(32),
        position: 'absolute',
        top: '50%',
        right: rpx(30),
        marginTop: -rpx(16),
        zIndex: 2,
    },
    text: {
        fontSize: rpx(32),
        color: '#3D3D3D',
        textAlign: 'center',
        marginTop: rpx(24),
    },
});

export default React.memo(Slider);