import {PermissionsAndroid, Platform, Text, TouchableOpacity, View} from "react-native";
import {useEffect, useState} from "react";
import {Permission} from "react-native/Libraries/PermissionsAndroid/PermissionsAndroid";
import RNBluetoothClassic, {BluetoothDevice} from "react-native-bluetooth-classic";
import {RFPercentage} from "react-native-responsive-fontsize";
import {responsiveWidth} from "react-native-responsive-dimensions";
import {blue, blueButton, red} from "../../css/colors";
import BasicButton from "../../components/BasicButton/BasicButton";
import {useSelector} from "react-redux";
import {RootState, useAppDispatch} from "../../redux/store";
import {setDevice, setIsConnected} from "../../features/scannerState/scannerState";
import {closeScanModal, setScannedData} from "../../features/scanModal/scanModalSlice";


type BluetoothSettingsState = {
    enabled: boolean;
    devices: BluetoothDevice[]
}
const DEFAULT_BLUETOOTH_SETTINGS_STATE: BluetoothSettingsState = {
    enabled: false,
    devices: []
}

function MoneyScreen() {
    const [state, setState] = useState<BluetoothSettingsState>(DEFAULT_BLUETOOTH_SETTINGS_STATE);
    const scannerState = useSelector((state: RootState) => state.scanner);
    const dispatch = useAppDispatch();

    async function requestBluetoothPermissions() {
        if (Platform.OS === 'android') {
            const permissions: Permission[] = [];

            if (Platform.Version >= 31) {  // Android 12+
                permissions.push(
                    PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
                    PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
                    PermissionsAndroid.PERMISSIONS.BLUETOOTH_ADVERTISE,
                    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
                );
                console.log("android12")
            } else {  // Below Android 12
                permissions.push(
                    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
                );
            }

            const granted = await PermissionsAndroid.requestMultiple(permissions);


            const hasBluetoothPermission =
                (Platform.Version >= 31 &&
                    granted['android.permission.BLUETOOTH_SCAN'] === PermissionsAndroid.RESULTS.GRANTED &&
                    granted['android.permission.BLUETOOTH_CONNECT'] === PermissionsAndroid.RESULTS.GRANTED) ||
                (Platform.Version < 31 &&
                    granted['android.permission.ACCESS_FINE_LOCATION'] === PermissionsAndroid.RESULTS.GRANTED);

            if (hasBluetoothPermission) {
                console.log('Bluetooth permissions granted');
            } else {
                console.warn('Bluetooth permissions denied');
            }
        }
    }

    const initialize = async () => {
        const isEnabled = await RNBluetoothClassic.isBluetoothEnabled();
        const devices = isEnabled ? await RNBluetoothClassic.getBondedDevices() : []
        setState(prevState => {
            return {
                ...prevState,
                enabled: isEnabled,
                devices: devices
            }
        })
    }
    const setSelectedDevice = (device: BluetoothDevice) => {
        dispatch(setDevice({deviceAddress: device.address}));
    }
    const onConnectPress = async () => {

        if (!scannerState.deviceAddress) return;
        if (scannerState.isConnected) {
            console.log("connected")
            await RNBluetoothClassic.disconnectFromDevice(scannerState.deviceAddress);
            return
        }
        console.log("connecting")
        const connected = await RNBluetoothClassic.connectToDevice(scannerState.deviceAddress, {
            secureSocket: false,
            charset: "UTF-8",
            delimiter: "\r\r"
        });
        const isConnected = await connected.isConnected();
        dispatch(setIsConnected({isConnected}));
        if (isConnected) {
            RNBluetoothClassic.onDeviceRead(connected.address, event => {
                dispatch(setScannedData(event.data));
                dispatch(closeScanModal())

            })
        }
    }
    useEffect(() => {
        const interval = setInterval(initialize, 1000);

        const {remove: removeOnConnectedListener} = RNBluetoothClassic.onDeviceConnected(event => {
            console.log("Connected event")
            dispatch(setIsConnected({isConnected: true}));

        })
        const {remove: removeOnDisconnectedListener} = RNBluetoothClassic.onDeviceDisconnected(event => {
            dispatch(setIsConnected({isConnected: false}));

        })
        return () => {
            clearInterval(interval);
            removeOnConnectedListener();
            removeOnDisconnectedListener()
        }

    }, []);
    return (
        <View style={{padding: "5%"}}>
            <Text>
                Блютуз включен: {state.enabled ? "да" : "нет"}
            </Text>
            <View
                pointerEvents={scannerState.isConnected ? "none" : "auto"}
                style={{opacity: scannerState.isConnected ? 0.4 : 1}}
            >

                {state.devices.map(device => (
                    <TouchableOpacity onPress={() => setSelectedDevice(device)} key={device.address}>
                        <View
                            style={{
                                backgroundColor: scannerState.deviceAddress == device.address ? blue : "white",
                                padding: RFPercentage(2),
                                borderRadius: responsiveWidth(2.5),
                                marginBottom: 10,

                            }}>
                            <Text style={{fontSize: RFPercentage(2)}}>
                                {device.name}
                            </Text>
                        </View>
                    </TouchableOpacity>
                ))}
            </View>

            <BasicButton
                onPress={onConnectPress}
                label={scannerState.isConnected ? "Отключить" : "Подключить"}
                style={{borderRadius: responsiveWidth(3), backgroundColor: scannerState.isConnected ? red : blueButton}}
            />
        </View>
    )
}

export default MoneyScreen;