import React, {FC, useEffect, useRef, useState} from "react";
import {Image, StyleSheet, TextInput, TouchableOpacity, View} from "react-native";
import {responsiveHeight, responsiveWidth} from "react-native-responsive-dimensions";
import {RFPercentage} from "react-native-responsive-fontsize";
import BasicButton from "../BasicButton/BasicButton";
import SelectProductModal from "../Modals/SelectProductModal/SelectProductModal";
import {SupplierProduct} from "../../types/supplierProduct";
import barcodeApi from "../../api/barcodeApi";
import {useDispatch, useSelector} from "react-redux";
import {openScanModal, setScannedData} from "../../features/scanModal/scanModalSlice";
import {RootState} from "../../redux/store";
import {Product} from "../../types/product";

type Props = {
    onSearch?: (text: string) => void;
    onProductSelected?: (product: Product) => void
}
const SearchBar: FC<Props> = ({onSearch, onProductSelected}) => {

    const dispatch = useDispatch();
    const [searchInput, setSearchInput] = useState<string>("");
    const textInputRef = useRef<TextInput>(null);
    const [products, setProducts] = useState<Product[]>([]);

    const scannedData = useSelector((state: RootState) => state.scanModal.scannedData);
    useEffect(() => {
        if (!scannedData) return;
        barcodeApi.searchProducts(scannedData).then((response) => {
            setProducts(response)
        });
    }, [scannedData]);
    useEffect(() => {
        if (products.length == 0 || products.length > 1 || !onProductSelected) return;
        onProductSelected(products[0]);
        setProducts([]);
        dispatch(setScannedData(undefined));
    }, [products]);
    const selectProductModalVisible = products.length > 1;
    return (
        <View style={styles.container}>
            <SelectProductModal visible={selectProductModalVisible}
                                products={products}
                                onSelected={(product) => {
                                    if (onProductSelected) onProductSelected(product);
                                    setProducts([]);
                                    dispatch(setScannedData(undefined));
                                }}/>
            <BasicButton onPress={() => {
                if (!onSearch) return;
                onSearch(searchInput);
                if (textInputRef.current) {
                    textInputRef.current.clear();
                }
            }} style={styles.scanButton} label={"Поиск"}/>
            <View style={styles.scanImageWrapper}>
                <TouchableOpacity onPress={() => {
                    dispatch(openScanModal());
                }}>
                    <Image style={styles.scanImage} source={require('assets/icons/scan.png')}/>
                </TouchableOpacity>
            </View>
            <TextInput ref={textInputRef} onChangeText={(text) => {
                setSearchInput(text);
            }} style={styles.textInput} placeholder={"Введите запрос"}/>
        </View>
    )
}

const height = 6;
const styles = StyleSheet.create({
    container: {
        display: "flex",
        flexDirection: "row-reverse",
        height: responsiveHeight(height),
        alignItems: "flex-end",
        backgroundColor: "white"
    },
    scanImage: {
        height: responsiveHeight(5),
        width: responsiveHeight(5),

    },
    scanButton: {
        borderRadius: 0,
        borderTopRightRadius: responsiveWidth(1),
        borderBottomRightRadius: responsiveWidth(1),
        paddingHorizontal: responsiveWidth(5),
        height: '100%'
    },
    scanImageWrapper: {
        paddingHorizontal: responsiveWidth(1),
        height: responsiveHeight(height),
        display: "flex",
        justifyContent: "center",
        borderWidth: 1,
        borderColor: "#A5A5A5",
    },
    textInput: {
        height: responsiveHeight(height),
        flex: 1,
        borderWidth: 1,
        borderColor: "#A5A5A5",
        borderTopLeftRadius: responsiveWidth(1),
        borderBottomLeftRadius: responsiveWidth(1),
        paddingLeft: responsiveHeight(2),
        fontSize: RFPercentage(2),
    }
})

export default SearchBar
