import React, { useState, useEffect, useRef } from 'react';
import Container from '../components/container';
import { useRoute } from '@react-navigation/native';
import { customStyles, GetPageTheme, deffontfamily } from "../styles/Global";
import { View, Text, TouchableOpacity, Platform, Animated, Alert, AppState, StyleSheet, SectionList } from 'react-native';
import { connect, } from 'react-redux';
import { mapStateToProps, mapDispatchToProps } from '../reducers/contextProvider';
import moment from 'moment';
import { db } from '../constants/constants';
import CustomHeader from '../components/customHeader';
import CustomLoader from '../components/CustomLoader';
import LinearGradient from 'react-native-linear-gradient';

function PrevOrders(props) {
    const route = useRoute();
    const ST = props.StaticText || {};
    const PageTheme = GetPageTheme(props.DarkMode, route.name);
    const customStyle = customStyles(props.DarkMode, route.name);
    const animatedChoice = useRef(new Animated.Value(0)).current;
    const [processing, setProcessing] = useState(true);
    const [loaderTitle, setLoaderTitle] = useState('loading...');

    const [storeData, setStoreData] = useState({});
    const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
    const hasUnsavedChangesRef = React.useRef(hasUnsavedChanges);
    const StoreIdRef = React.useRef(null);
    const prevScreenRef = React.useRef("");
    const d1 = new Date();
    const d2 = moment(d1).format('MM/DD/YYYY');
    const [orders, setOrders] = useState([]); // raw data
    const [sections, setSections] = useState([]); // grouped data
    const [expandedSections, setExpandedSections] = useState({}); // key: true/false
    // ✅ Group by StorePO + SystemPO
    const groupOrders = (data, prevScreen) => {
        const grouped = {};
        data.forEach((item) => {
            if (prevScreen != "") {
                const key = `${item.VisitDate}_${item.StoreId}`;
                if (!grouped[key]) {
                    grouped[key] = {
                        VisitDate: item.VisitDate,
                        StoreId: item.StoreId,
                        data: [],
                    };
                }
                grouped[key].data.push({
                    ProductName: item.ProductName,
                    OrderQty: item.OrderQty,
                    PackType: item.PackType
                });
            } else {
                const key = `${item.StorePO}_${item.SystemPO}`;
                if (!grouped[key]) {
                    grouped[key] = {
                        StorePO: item.StorePO,
                        SystemPO: item.SystemPO,
                        ContactName: item.ContactName,
                        ContactNo: item.ContactNo,
                        VisitDate: item.VisitDate,
                        data: [],
                    };
                }
                grouped[key].data.push({
                    ProductName: item.ProductName,
                    OrderQty: item.OrderQty,
                });
            }
        });

        return Object.values(grouped);
    };

    const toggleSection = (key) => {
        setExpandedSections((prev) => ({
            ...prev,
            [key]: !prev[key],
        }));
    };

    useEffect(() => {
        const params = props.route.params || {};
        const storeData1 = params.storeData || {};
        const prevScreen = params.prevScreen || "";
        prevScreenRef.current = prevScreen;
        setStoreData(storeData1);
        console.log("Store_data", prevScreen, storeData1);
        getData(storeData1, prevScreen);
        StoreIdRef.current = storeData1.StoreId;
        if (storeData1.StoreId) {
            getData(storeData1, prevScreen);
        }

        const AppStateSubscription = AppState.addEventListener('change', _handleAppStateChange);
        const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);

        return () => {
            AppStateSubscription.remove();
            unsubscribe();
        };
    }, [props.route.params]); // <-- only re-run when route params change


    const _handleAppStateChange = async (nextAppState) => {
        if (nextAppState === 'background' && hasUnsavedChangesRef.current === true) {
        }
    };

    useEffect(() => {
        const unsubscribe = props.navigation.addListener('beforeRemove', onBeforeRemove);
        return unsubscribe;
    }, [hasUnsavedChanges]);

    function onBeforeRemove(e) {
        if (hasUnsavedChanges === true) {
            e.preventDefault();
            onRemoveScreen(e);
        } else {
            return;
        }
    }


    function onRemoveScreen(e) {
        Alert.alert(
            "",
            "Do you really want to exit the screen?",
            [
                {
                    text: "Cancel",
                    onPress: () => { },
                    style: "cancel"
                },
                {
                    text: "OK", onPress: async () => {
                        props.navigation.dispatch(e.data.action);
                    }
                }
            ]
        );
    }

    async function getData(storeData1, prevScreen) {
        try {
            const { StoreId } = storeData1;
            db.transaction((txn) => {
                const tableName =
                    prevScreen !== "" ? "PriviousVisit_OrdersSimplyfyHistory" : "PriviousVisit_OrdersHistory";

                const query = `SELECT * FROM ${tableName} WHERE StoreId=${StoreId}`;
                txn.executeSql(
                    query,
                    null, // filter by StoreId if needed
                    (txn, res) => {
                        let arr = [];
                        for (let i = 0; i < res.rows.length; i++) {
                            arr.push(res.rows.item(i));
                        }
                        console.log("arr", arr)
                        setOrders(arr);
                        const groupedSections = groupOrders(arr, prevScreen);
                        setSections(groupedSections);
                        // ✅ Expand the first section only
                        if (groupedSections.length > 0) {
                            const firstKey = prevScreen != "" ? `${groupedSections[0].VisitDate}_${groupedSections[0].StoreId}` : `${groupedSections[0].StorePO}_${groupedSections[0].SystemPO}`;
                            setExpandedSections({ [firstKey]: true });
                        }

                        setProcessing(false);
                    },
                    (txn, err) => {
                        console.log("SQLite Error:", err);
                        setProcessing(false);
                    }
                );
            });
        } catch (err) {
            console.log(err);
            setProcessing(false);
        }
    }

    return (
        <Container {...props} pt={0} avoidSafeArea={(Platform.OS == 'ios' ? true : false)}>
            {processing && <CustomLoader fullHeight={true} title={loaderTitle} />}
            <CustomHeader {...props} showaddstore={true} title="Prev. Orders" projectCode={`${storeData.StoreId}: ${storeData.StoreName}`} />
            <LinearGradient colors={[PageTheme.$gradient1, PageTheme.$primary_color]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={customStyle.roundScrollWrapper}>
                <View style={[customStyle.pageContentWrapper]}>
                    {console.log("sections", sections)}
                    <View style={{ flex: 1 }}>
                        {sections.length > 0 ? (
                            <SectionList
                                sections={sections.map(section => {
                                    const key = prevScreenRef.current != "" ? `${section.VisitDate}_${section.StoreId}` : `${section.StorePO}_${section.SystemPO}`;
                                    return {
                                        ...section,
                                        data: expandedSections[key] ? section.data : [], // show data only if expanded
                                    };
                                })}
                                keyExtractor={(item, index) => item.ProductName + index}
                                renderItem={({ item }) => (

                                    prevScreenRef.current !== "" ? (
                                        <View
                                            style={[
                                                styles.itemCard,
                                                {
                                                    backgroundColor: PageTheme.$secondary_color_light,
                                                    flexDirection: "row",      // main row
                                                    justifyContent: "space-between",
                                                    alignItems: "center",
                                                    padding: 8,
                                                },
                                            ]}
                                        >
                                            {/* Left side: ProductName and PackType stacked vertically */}
                                            <View style={{ flexDirection: "column" }}>
                                                <Text style={styles.product}>Product: {item.ProductName}</Text>
                                                {item.PackType && (
                                                    <Text style={styles.product}>PackType: {item.PackType}</Text>
                                                )}

                                            </View>

                                            {/* Right side: Orders */}
                                            <Text style={[styles.qty, { textAlign: "right" }]}>Orders: {item.OrderQty}</Text>
                                        </View>

                                    ) : (
                                        <View style={[styles.itemCard, { backgroundColor: PageTheme.$secondary_color_light }]}>
                                            <Text style={styles.product}>{item.ProductName}</Text>
                                            <Text style={styles.qty}>Orders : {item.OrderQty}</Text>
                                        </View>
                                    )

                                )}

                                renderSectionHeader={({ section }) => {
                                    const key = prevScreenRef.current !== "" ? `${section.VisitDate}_${section.StoreId}` : `${section.StorePO}_${section.SystemPO}`;
                                    const isExpanded = expandedSections[key];
                                    return (
                                        <TouchableOpacity style={[customStyle.opening_Stock_cat]} onPress={() => toggleSection(key)}>
                                            <LinearGradient
                                                colors={[PageTheme.$primary_color, PageTheme.$secondary_color_light]}
                                                start={{ x: 0, y: 0 }}
                                                end={{ x: 1, y: 1 }}
                                                style={[{
                                                    paddingHorizontal: 10,
                                                    paddingVertical: 7,
                                                    backgroundColor: PageTheme.$primary_color,
                                                    borderRadius: 5,
                                                    marginStart: 8,
                                                    marginRight: 8
                                                }]}

                                            >
                                                <View style={styles.headerRow}>
                                                    <Text style={styles.expandIcon}>{isExpanded ? '▼' : '▶'}</Text>
                                                    <View style={{ marginLeft: 3 }}>
                                                        {prevScreenRef.current !== "" ? (
                                                            <>
                                                                <Text style={styles.headerTitle}>
                                                                    Order Date : {section.VisitDate}
                                                                </Text>
                                                                <Text style={styles.headerTitle}>
                                                                    Store Info : {section.StoreId}: {storeData.StoreName}
                                                                </Text>
                                                            </>
                                                        ) : (
                                                            <>
                                                                <Text style={styles.headerTitle}>
                                                                    Store PO : {section.StorePO} - {section.VisitDate}
                                                                </Text>
                                                                <Text style={styles.headerTitle}>
                                                                    System PO : {section.SystemPO}
                                                                </Text>
                                                                {section.ContactName && (
                                                                    <Text style={styles.contact}>
                                                                        User Info : {section.ContactName} ({section.ContactNo})
                                                                    </Text>
                                                                )}

                                                            </>
                                                        )}
                                                    </View>
                                                </View>
                                            </LinearGradient>

                                        </TouchableOpacity>
                                    );
                                }}
                                stickySectionHeadersEnabled={false}
                                contentContainerStyle={{ paddingBottom: 20 }}
                            />
                        ) : (
                            <View style={styles.noOrdersContainer}>
                                <Text style={styles.noOrdersText}>No Previous Orders Found !!</Text>
                            </View>
                        )}
                    </View>


                </View>
            </LinearGradient>

        </Container>
    );
}


export default connect(mapStateToProps, mapDispatchToProps)(PrevOrders);

const styles = StyleSheet.create({
    sectionHeader: {
        backgroundColor: '#e0e4faff',
        padding: 10,
        borderRadius: 12,
        marginVertical: 6,
        marginHorizontal: 10,
    },
    headerRow: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    headerTitle: {
        fontSize: 15,
        fontWeight: 'bold',
        color: 'white',
    },
    expandIcon: {
        fontSize: 20,
        fontWeight: 'bold',
        color: 'white',
        marginHorizontal: 5,
    },
    contact: {
        fontSize: 14,
        color: 'white',
        marginTop: 4,
        marginStart: 5
    },
    itemCard: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        padding: 12,
        marginHorizontal: 16,
        marginVertical: 4,
        borderRadius: 5,
        elevation: 1,
        shadowColor: '#484848',
        shadowOpacity: 0.1,
        shadowOffset: { width: 0, height: 2 },
    },
    product: {
        color: '#333',
        fontFamily: deffontfamily,
        fontWeight: '600',
        fontSize: 14,

    },
    qty: {
        fontSize: 15,
        fontWeight: '600',
        color: '#000',

    },
    headerRow: {
        flexDirection: 'row',
        alignItems: 'center', // vertically center the icon with texts
    },
    noOrdersContainer: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    noOrdersText: {
        color: 'red',
        fontSize: 18,
        fontWeight: 'bold',
    },
});

