import React, { useEffect, useRef, useState } from 'react';
import {
    StyleSheet,
    TouchableWithoutFeedback,
    Animated,
    Dimensions,
    Keyboard,
    ScrollView,
    Platform,
} from 'react-native';
import { View, Text, useTheme } from '@bettoredge/styles';
import type { CalcuttaEscrowProps } from '@bettoredge/types';
import type { CalcuttaLifecycleState } from '../../helpers/lifecycleState';
import { canManageEscrow } from '../../helpers/lifecycleState';
import { CalcuttaEscrow } from '../CalcuttaEscrow';

interface EscrowBottomSheetProps {
    visible: boolean;
    onDismiss: () => void;
    calcutta_competition_id: string;
    escrow?: CalcuttaEscrowProps;
    market_type: string;
    max_escrow?: number;
    player_balance?: number;
    onDepositFunds?: (amount: number) => void;
    onUpdate: () => void;
    lifecycleState: CalcuttaLifecycleState;
}

const SCREEN_HEIGHT = Dimensions.get('window').height;

export const EscrowBottomSheet: React.FC<EscrowBottomSheetProps> = ({
    visible,
    onDismiss,
    calcutta_competition_id,
    escrow,
    market_type,
    max_escrow,
    player_balance,
    onDepositFunds,
    onUpdate,
    lifecycleState,
}) => {
    const { theme } = useTheme();
    const slideAnim = useRef(new Animated.Value(SCREEN_HEIGHT)).current;
    const overlayAnim = useRef(new Animated.Value(0)).current;
    const [keyboardHeight, setKeyboardHeight] = useState(0);
    const readOnly = !canManageEscrow(lifecycleState);

    useEffect(() => {
        const showSub = Keyboard.addListener(
            Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow',
            (e) => setKeyboardHeight(e.endCoordinates.height),
        );
        const hideSub = Keyboard.addListener(
            Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide',
            () => setKeyboardHeight(0),
        );
        return () => {
            showSub.remove();
            hideSub.remove();
        };
    }, []);

    useEffect(() => {
        if (visible) {
            Animated.parallel([
                Animated.timing(slideAnim, {
                    toValue: 0,
                    duration: 300,
                    useNativeDriver: true,
                }),
                Animated.timing(overlayAnim, {
                    toValue: 1,
                    duration: 300,
                    useNativeDriver: true,
                }),
            ]).start();
        } else {
            Keyboard.dismiss();
            Animated.parallel([
                Animated.timing(slideAnim, {
                    toValue: SCREEN_HEIGHT,
                    duration: 250,
                    useNativeDriver: true,
                }),
                Animated.timing(overlayAnim, {
                    toValue: 0,
                    duration: 250,
                    useNativeDriver: true,
                }),
            ]).start();
        }
    }, [visible]);

    const handleDismiss = () => {
        Keyboard.dismiss();
        onDismiss();
    };

    if (!visible) return null;

    return (
        <View variant="transparent" style={StyleSheet.absoluteFill}>
            {/* Overlay — tapping dismisses keyboard + modal */}
            <TouchableWithoutFeedback onPress={handleDismiss}>
                <Animated.View style={[styles.overlay, { opacity: overlayAnim }]} />
            </TouchableWithoutFeedback>

            {/* Sheet */}
            <Animated.View
                style={[
                    styles.sheet,
                    {
                        backgroundColor: theme.colors.surface.base,
                        transform: [{ translateY: slideAnim }],
                        maxHeight: SCREEN_HEIGHT * 0.85,
                        paddingBottom: Math.max(40, keyboardHeight),
                    },
                ]}
            >
                {/* Handle — tapping dismisses keyboard */}
                <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
                    <View variant="transparent" style={styles.handleArea}>
                        <View variant="transparent" style={[styles.handle, { backgroundColor: theme.colors.border.default }]} />
                        <Text variant="body" bold style={styles.title}>
                            {readOnly ? 'Escrow Balance' : 'Manage Escrow'}
                        </Text>
                    </View>
                </TouchableWithoutFeedback>

                <ScrollView
                    keyboardShouldPersistTaps="handled"
                    showsVerticalScrollIndicator={false}
                    bounces={false}
                >
                    <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
                        <View variant="transparent">
                            <CalcuttaEscrow
                                calcutta_competition_id={calcutta_competition_id}
                                escrow={escrow}
                                market_type={market_type}
                                max_escrow={max_escrow}
                                player_balance={player_balance}
                                onDepositFunds={onDepositFunds}
                                onUpdate={onUpdate}
                                readOnly={readOnly}
                            />
                        </View>
                    </TouchableWithoutFeedback>
                </ScrollView>
            </Animated.View>
        </View>
    );
};

const styles = StyleSheet.create({
    overlay: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: 'rgba(0,0,0,0.4)',
    },
    sheet: {
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        borderTopLeftRadius: 16,
        borderTopRightRadius: 16,
    },
    handleArea: {
        alignItems: 'center',
        paddingTop: 10,
        paddingBottom: 4,
    },
    handle: {
        width: 36,
        height: 4,
        borderRadius: 2,
    },
    title: {
        textAlign: 'center',
        marginTop: 8,
        marginBottom: 4,
    },
});
