import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { ScrollView, View, Text, Image, TouchableOpacity, BackHandler, Dimensions, Keyboard, ImageBackground } from 'react-native';
import { FontAwesome, Ionicons } from '@expo/vector-icons';
import config from '../../components/data/config.json'
import { styles } from '@/components/style/style';
import { FAB } from 'react-native-elements';
import { useNavigation, NavigationProp, useFocusEffect } from '@react-navigation/native';
import { GestureHandlerRootView, TextInput } from 'react-native-gesture-handler';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { addStorage, cfg, getStorage } from '@/components/lib/cfg';
import { DB } from '@/components/lib/db';
import { LineChart } from 'react-native-chart-kit';
import Nav from '@/components/nav';


const ProfileSreen = forwardRef((props, ref) => {
    const [bgHead, setBgHead] = useState<any>(null)
    const [nama, setNama] = useState('John Doe');
    const [Id, setId] = useState('John Doe');
    const [formTitle, setFormTitle] = useState('Perusahaan');
    const [formArea, setFormArea] = useState('none');
    const [email, setEmail] = useState('example@mail.com');
    const [inputVal, setInputVal] = useState('');
    const [formName, setFormName] = useState('');
    const [datatext, setDataText] = useState('example@mail.com');
    const inputRef = useRef<TextInput>(null); // Create a ref for the TextInput
    let heightWIndow = Dimensions.get('window').height + 80;
    const [contact, setContact] = useState<{
        name: string
        , row: string
        , icon: string
        , value: string
        , type: string | null
    }[]>([]);
    const [produk, setProduk] = useState<{
        name: string
        , value: string
    }[]>([]);

    

    const navigation = useNavigation<NavigationProp<RootStackParamList>>();

   

    const Contact = (props: any) => {
        return (
            <>
                {(props?.data || []).map((data: any, key: number) =>
                    <TouchableOpacity key={key}>
                        <View style={[
                            { padding: 10, borderTopColor: "#ddd", borderTopWidth: key == 0 ? 0 : 1 }
                            , { flexDirection: "row", alignItems: "center" }
                        ]}>
                            <View style={[{ flexDirection: "row" }, { flex: 1 }]}>
                                {data.type == 'ionic' ?
                                    <Ionicons name={data?.icon} style={[{ paddingHorizontal: 0, width: 20 }, styles.icon]} />
                                    :
                                    <FontAwesome name={data?.icon} style={[{ paddingHorizontal: 5, width: 20 }, styles.icon]} />
                                }
                                <Text ellipsizeMode='tail' style={[{ flex: 1 }, styles.contactText, data.value ? { color: "#333" } : { color: "#aaa" }]}>{data.value ? data.value : data.name}</Text>
                            </View>
                            <View>
                                {/* <View style={{
                                    width:30
                                    , height:30
                                    , flexDirection:'row'
                                    , backgroundColor:'lightgray'
                                    , borderRadius:20
                                    , justifyContent:'center'
                                    , alignItems:'center'
                                }}>
                                    <FontAwesome name={"pencil"} style={{fontSize:18}} />
                                </View> */}
                            </View>
                        </View>
                    </TouchableOpacity>
                )}
            </>
        )
    }

    useFocusEffect(
        React.useCallback(() => {
            
            callData();

            const onBackPress = () => {
                navigation.navigate("home");
                return true; // Prevent default behavior (exit app)
            };

            BackHandler.addEventListener('hardwareBackPress', onBackPress);
            navigation.setOptions({ headerLeft: () => null }); // Remove back button

            return () => {
                BackHandler.removeEventListener('hardwareBackPress', onBackPress);
            };

        }, [navigation, callData])
    );

    

    const callData = async () => {


        let data: any = await AsyncStorage.getItem('login');
        data = JSON.parse(data);
        data = data.length>0?data[0]:{};
        let [nameCompany]: any = await DB(`SELECT name FROM res_company WHERE id = ${data?.company_id}`);

        console.log(data)

        setId(data?.id)
        setNama(data?.name)
        setEmail("Salesman")

        let country = 'Indonesia';
        if (data?.country_id) {
            const negara: any = await getStorage('negara')
            const [{ name }] = negara.filter((s: any) => s?.id == data?.country_id);
            country = name;
        }

        setContact([
            {
                name: "Name",
                row: "name",
                icon: "mail-outline",
                value: data?.work_email,
                type: "ionic"
            }
            , {
                name: "Email",
                row: "email",
                icon: "logo-whatsapp",
                value: data?.work_phone,
                type: "ionic"
            }
            , {
                name: "Company Name",
                row: "company_id",
                icon: "location-outline",
                value: nameCompany?.name,
                type: "ionic"
            }
            , {
                name: "Address",
                row: "company_id",
                icon: "location-outline",
                value: data?.private_street,
                type: "ionic"
            }
        ]);

    };

    useImperativeHandle(ref, () => ({
        loadData() {
            console.log('Data di ContactScreen sedang di-load...');
            // Lakukan operasi loading data di sini
        },
    }));

    useEffect(() => {
        (function () {
            callData()
        })();

    }, [])

    const customerBack = function () {
        navigation.navigate('home')
    }

    const fabAction = function () {
        // console.log("action")
    }

    const onScroll = (event: any) => {
        const yOffset = event.nativeEvent.contentOffset.y;
        if (yOffset > 190) {
            setBgHead(config.color.primary)
        } else {
            setBgHead(null)
        }
    };


    return (
        <>
            <GestureHandlerRootView>
                
                    <View style={[{
                        top: 0,
                        left: 0,
                        right: 0,
                        backgroundColor: bgHead != '' ? bgHead : 'none',
                        padding: 10,
                        zIndex: 3, // Make sure it stays on top of other content
                    }, styles.flexStartBottom, { width: '100%', height: 80, justifyContent: 'flex-start', position: 'absolute', top: 0 }]}>
                        <TouchableOpacity onPress={customerBack}>
                            <Ionicons style={{ padding: 8, marginHorizontal: 8, borderRadius: 30, backgroundColor: "rgba(0,0,0,.2)" }} name='arrow-back-outline' size={20} color={'white'}></Ionicons>
                        </TouchableOpacity>
                    </View>
                <ScrollView onScroll={onScroll}>
                    <View style={styles.container}>
                        <ImageBackground
                            source={require('../../assets/images/bg/SORT_bg_Order.png')}
                            style={{
                                flexDirection: "row"
                                , alignItems: 'flex-end'
                                , top: 0
                                , height: 300
                            }}
                        >
                            <View style={[{ paddingVertical: 20, paddingBottom:30, width:"100%" }, styles.header]}>
                                <Image
                                    source={{ uri: 'https://img.freepik.com/free-photo/portrait-white-man-isolated_53876-40306.jpg' }}
                                    style={[styles.profilePic]}
                                />
                                <Text style={[styles.name, { fontSize : 24, color: "white" }]}>{nama.toLocaleUpperCase()}</Text>
                                <Text style={[styles.jobTitle, { fontSize:16, color: "white" }]}>{email}</Text>
                            </View>
                        </ImageBackground>


                        <View style={{paddingHorizontal:20, paddingVertical:10}}>
                            <View style={{
                                backgroundColor:config.color.primary
                                , padding: 10
                                , paddingVertical: 20
                                , borderRadius: 15
                                , flexDirection: 'row'
                            }}>
                                <View style={{flex:1}}>
                                    <Text style={{
                                        fontSize : 12
                                        , color: '#fff'
                                        , fontWeight: '600'
                                        , textAlign: 'center'
                                    }}>SALES TODAY</Text>
                                    <Text style={{
                                        fontSize: 24
                                        , color: '#fff'
                                        , fontWeight: 'bold'
                                        , textAlign: 'center'
                                    }}>200</Text>
                                </View>
                                <View style={{flex:1}}>
                                    <Text style={{
                                        fontSize : 12
                                        , color: '#fff'
                                        , fontWeight: '600'
                                        , textAlign: 'center'
                                    }}>OVERAL SALES</Text>
                                    <Text style={{
                                        fontSize: 24
                                        , color: '#fff'
                                        , fontWeight: 'bold'
                                        , textAlign: 'center'
                                    }}>200</Text>
                                </View>
                                <View style={{flex:1}}>
                                    <Text style={{
                                        fontSize : 12
                                        , color: '#fff'
                                        , fontWeight: '600'
                                        , textAlign: 'center'
                                    }}>RANKING</Text>
                                    <View style={{
                                        flexDirection: 'row'
                                        , justifyContent: 'center'
                                    }}>
                                        <View>
                                            <Text style={{
                                                fontSize: 24
                                                , color: '#fff'
                                                , fontWeight: 'bold'
                                                , textAlign: 'center'
                                            }} >1</Text>
                                        </View>
                                        <View>
                                            <Text style={{
                                                fontSize: 12
                                                , color: '#fff'
                                                , fontWeight: 'bold'
                                                , textAlign: 'center'
                                            }}>st</Text>
                                        </View>
                                    </View>
                                </View>
                            </View>
                        </View>

                        <View>
                            <Text style={{
                                textAlign: "center"
                                ,fontSize: 24
                                ,fontWeight: '600'
                                ,color: '#555'
                                ,paddingVertical: 10 
                            }}>Detail Information</Text>
                        </View>
                        <View style={[{ paddingHorizontal: 20, paddingVertical: 5, backgroundColor: 'white' }]}>
                            <Contact data={contact}></Contact>
                        </View>
                    </View>
                </ScrollView>
                <Nav/>
            </GestureHandlerRootView>
        </>
    );
});


export default ProfileSreen;