import {StyleSheet, TextInput, View} from "react-native";
import {responsiveHeight, responsiveWidth} from "react-native-responsive-dimensions";
import {blue} from "../../css/colors";
import {RFPercentage} from "react-native-responsive-fontsize";
import DTitle from "../../components/DTitle/DTitle";
import Separator from "../../components/Separator/Separator";
import {useCallback, useEffect, useState} from "react";
import {useSelector} from "react-redux";
import SettingsView from "./SettingsView";
import TransactionsView from "./TransactionView";
import {RootState, useAppDispatch} from "../../redux/store";
import {fetchBalance, fetchTransactions, refreshTransactions} from "../../features/balance/balanceSlice";
import {formatBalanceNumber} from "../../utils/formatters";
import {debounce} from 'lodash';
import * as SecureStore from 'expo-secure-store';


function ProfileScreen() {
    const dispatch = useAppDispatch();
    const loadPrinterIp = async () => {
        try {
            const value = await SecureStore.getItemAsync("printerIp");
            if (value) {
                setPrinterIp(value);
            }
        } catch (error) {
            console.error("Error loading printer IP from secure store:", error);
        }
    }
    const [printerIp, setPrinterIp] = useState<string>("");
    const [printerIpDebounce, setPrinterIpDebounce] = useState<string>(printerIp);
    const debouncedSetValue = useCallback(
        debounce((value: string) => {
            setPrinterIpDebounce(value);
        }, 200), // 500ms debounce delay
        []
    );
    const balanceState = useSelector((state: RootState) => state.balance);
    const onTransactionsEndReached = () => {
        if (balanceState.transactions.isLoading || !balanceState.transactions.hasNext) return;
        dispatch(fetchTransactions(balanceState.transactions.currentPage));
    };

    const onTransactionsRefresh = () => {
        dispatch(refreshTransactions());
    }
    useEffect(() => {
        loadPrinterIp();
        dispatch(fetchBalance());
    }, []);

    function onPrinterIpChange(text: string) {
        setPrinterIp(text);
        debouncedSetValue(text);
    }

    useEffect(() => {
        if (printerIpDebounce.length > 0) {
            SecureStore.setItemAsync("printerIp", printerIpDebounce).then(() => {
            }).catch((error) => {
                console.error("Error saving printer IP to secure store:", error);
            });
        }
    }, [printerIpDebounce]);

    return (
        <View style={styles.container}>

            <View style={styles.header}>
                <View style={styles.headerInfo}>
                    <DTitle style={styles.headerText}>Ваш
                        баланс: {formatBalanceNumber(balanceState.balance, false)} руб</DTitle>
                </View>

            </View>
            <View style={styles.printerInputView}>
                <TextInput onChangeText={onPrinterIpChange} defaultValue={printerIp} style={styles.printerInput}
                           placeholderTextColor={"black"} placeholder={"IP принтера"}/>
            </View>
            <View style={styles.content}>
                <View style={styles.actionsCarouselContainer}>
                    <SettingsView/>
                </View>


                <Separator/>
                <View style={styles.historyContainer}>
                    <DTitle>История операций</DTitle>
                    <TransactionsView
                        onRefresh={onTransactionsRefresh}
                        isLoading={balanceState.transactions.isLoading}
                        transactions={balanceState.transactions.items}
                        onEndReached={onTransactionsEndReached}/>
                </View>
            </View>

        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        // backgroundColor: "red",
        flex: 1,
        display: "flex",
        flexDirection: "column",
    },
    overlay: {
        ...StyleSheet.absoluteFillObject,  // Это заполнит родительский элемент абсолютным позиционированием
        backgroundColor: 'rgba(104, 104, 104, 0.50)',
        zIndex: 2,  // Значение zIndex больше, чем у content, поэтому overlay будет выше
    },
    historyElementContainer: {
        width: "100%",
        backgroundColor: "white",
        borderRadius: RFPercentage(2),
        padding: RFPercentage(2),
        elevation: 1
    },
    historyContainer: {
        paddingVertical: responsiveHeight(2),
        flex: 1,
        gap: responsiveHeight(1),
        marginBottom: responsiveHeight(6)
    },
    historyElements: {
        marginTop: responsiveHeight(3),
    },
    historyElementsContainer: {
        rowGap: responsiveHeight(2),
    },
    header: {
        backgroundColor: blue,
        borderBottomLeftRadius: RFPercentage(3),
        borderBottomRightRadius: RFPercentage(3),
        elevation: 10,
        paddingHorizontal: responsiveWidth(5),
        paddingVertical: responsiveHeight(3),
        color: "white",
        display: "flex",
        flexDirection: "row"
    },
    headerText: {
        color: "white"
    },
    headerInfo: {
        // backgroundColor: "red"
    },
    actionsCarousel: {
        flexDirection: "row",
        columnGap: responsiveWidth(3),
    },
    actionsCarouselContainer: {
        // backgroundColor: "red",
        paddingVertical: responsiveHeight(5)
    },
    actionsCarouselImage: {
        resizeMode: "contain",
        flex: 1,
        width: "100%",
        height: "100%",
    },
    actionsCarouselImageWrapper: {
        width: RFPercentage(10),
        height: RFPercentage(10),
        backgroundColor: "white",
        borderRadius: 100,
        borderWidth: RFPercentage(0.3),
        padding: RFPercentage(1.5),
        justifyContent: "center",
        alignItems: "center"

    },
    actionsCarouselElementContainer: {
        display: "flex",
        alignItems: "center",

    },
    content: {
        flex: 1,
        paddingHorizontal: responsiveWidth(5),
    },
    printerInputView: {
        margin: responsiveHeight(2),
        backgroundColor: "white",
        borderRadius: RFPercentage(2),
        padding: RFPercentage(1),
        elevation: 1,
        marginBottom: responsiveHeight(3),
        color: "black",
    },
    printerInput: {
        // text color in input is black
        color: "black",

    }
})
export default ProfileScreen;