import {FC, useEffect, useRef} from "react";
import {StyleSheet, TextInput, View} from "react-native";
import {responsiveHeight, responsiveWidth} from "react-native-responsive-dimensions";
import {RFPercentage} from "react-native-responsive-fontsize";
import Modal from "react-native-modal";
import BasicButton from "../BasicButton/BasicButton";
import DText from "../DText/DText";
import {useDispatch, useSelector} from "react-redux";
import {RootState} from "../../redux/store";
import {closeScanModal, setScannedData} from "../../features/scanModal/scanModalSlice";

const ScanModal: FC = () => {
    const inputRef = useRef<TextInput | null>(null);
    const scannerState = useSelector((state: RootState) => state.scanner);
    const state = useSelector((state: RootState) => state.scanModal);
    const getDefaultLabel = () => "Наведите сканер на штрихкод товара или заказа";
    const dispatch = useDispatch();
    useEffect(() => {
        if (state.isVisible) inputRef.current?.focus();
    }, [state.isVisible]);

    return (
        <Modal isVisible={state.isVisible}>
            <View style={styles.container}>
                <DText style={styles.text}>{state.customLabel || getDefaultLabel()}</DText>
                <BasicButton onPress={() => {
                    dispatch(closeScanModal());
                }} style={styles.cancelButton} label={"Отмена"}/>
                <TextInput
                    onEndEditing={(e) => {
                        dispatch(setScannedData(e.nativeEvent.text));
                        dispatch(closeScanModal())
                    }}
                    style={styles.pseudoInput}
                    ref={inputRef}
                    autoFocus={true}
                    // showSoftInputOnFocus={false}
                />
            </View>
        </Modal>
    )
}

const styles = StyleSheet.create({
    container: {
        borderRadius: responsiveWidth(2),
        backgroundColor: "white",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        paddingHorizontal: responsiveWidth(18),
        paddingVertical: responsiveHeight(10),
        gap: responsiveHeight(3)
    },
    text: {
        color: "#2B2D3A",
        fontSize: RFPercentage(3),
        textAlign: "center"
    },
    cancelButton: {
        flex: 0,
        width: responsiveWidth(30)
    },
    pseudoInput: {
        opacity: 0,
        position: "absolute",
        zIndex: -1
    }
})
export default ScanModal;