import React, { useEffect, useRef, useState } from 'react';
import { ScrollView, View, Text, Image, TouchableOpacity, BackHandler, Dimensions, Keyboard } 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';


const CustDetail = ({ act, hidedata, search, show, data:dataRow, send }:any) => {
    const [bgHead, setBgHead] = useState<any>(null)
    const [nama, setNama] = useState('');
    const [Id, setId] = useState('');
    const [formTitle, setFormTitle] = useState('Perusahaan');
    const [formArea, setFormArea] = useState('none');
    const [email, setEmail] = useState('');
    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 [Act, setAct] = useState<any>(send['contactActiveData'])
    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} onPress={(attribs) => {
                        setFormArea('flex')
                        setFormTitle(data?.name);
                        setInputVal(data?.value)
                        setFormName(data?.row)
                        inputRef.current?.focus()
                    }}>
                        <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>
                            <FontAwesome name={"pencil"} style={[styles.icon, { marginHorizontal: 10 }]} />
                        </View>
                    </TouchableOpacity>
                )}
            </>
        )
    }


    const Produk = function (props: any) {
        return (
            <>
                <View style={[{ backgroundColor: 'white', padding: 20, height: 'auto', marginTop: 10 }]}>
                    <View style={{ marginBottom: 10, flexDirection: 'row', justifyContent: 'center' }}>
                        <Text style={{ flex: 1, marginBottom: 10, fontSize: 16, fontWeight: 400 }}>Riwayat Pembelian</Text>
                    </View>
                    <ScrollView showsHorizontalScrollIndicator={false} horizontal={true} style={{ width: "100%", flexDirection: 'row' }}>
                        {(props?.data || []).map((data: any, key: number) =>
                            <TouchableOpacity key={key}>
                                <View style={[{ width: 100, marginHorizontal: 5, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', borderRadius: 10, height: 50, backgroundColor: config.color.primary, padding: 10 }]}>
                                    <Text style={{ color: 'white' }}>{data?.name}</Text>
                                </View>
                            </TouchableOpacity>
                        )}
                    </ScrollView>
                </View>
            </>
        )
    }

    const callData = async (Active:any = null) => {

        let data: any = Active? Active : send['contactActiveData'];
        console.log(send)
        data = JSON.parse(atob(data));

        setId(data?.id)

        setNama(data?.name)
        setEmail(data?.email)

        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: "person",
                value: data?.name,
                type: "ionic"
            }
            , {
                name: "Email",
                row: "email",
                icon: "mail-outline",
                value: data?.email,
                type: "ionic"
            }
            , {
                name: "Company Name",
                row: "company_id",
                icon: "building",
                value: "PT VDS",
                type: ""
            }
            , {
                name: "Job Title",
                row: "function",
                icon: "star-outline",
                value: data?.function,
                type: "ionic"
            }
            , {
                name: "Phone",
                row: "phone",
                icon: "phone",
                value: data?.phone,
                type: ""
            }
            , {
                name: "Mobile Phone",
                row: "mobile",
                icon: "mobile",
                value: data?.mobile,
                type: ""
            }
            , {
                name: "Address",
                row: "street",
                icon: "location",
                value: data?.street,
                type: "ionic"
            }
            , {
                name: "Address 2",
                row: "street2",
                icon: "location",
                value: data?.street2,
                type: "ionic"
            }
            , {
                name: "City",
                row: "city",
                icon: "location",
                value: data?.city,
                type: "ionic"
            }
            , {
                name: "Country",
                row: "country_id",
                icon: "globe",
                value: country,
                type: "ionic"
            }
        ]);


        setProduk([
            {
                name: 'A1-F12',
                value: '20'
            }
            , {
                name: 'A1-K12',
                value: '20'
            }
            , {
                name: 'A1-F16',
                value: '20'
            }
            , {
                name: 'A1-F16',
                value: '20'
            }
        ]);
    };

    cfg.action['detailcontact'] = () => {
        callData()
    }

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

    }, [])

    const customerBack = function () {
        show(dataRow);
        hidedata(false)
        act(search)
    }

    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={[{
                    position: 'absolute',
                    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}>
                        <View style={[{ paddingVertical: 20 }, styles.header, { backgroundColor: config.color.primary }]}>
                            <Image
                                source={{ uri: 'https://img.freepik.com/free-photo/portrait-white-man-isolated_53876-40306.jpg' }}
                                style={[styles.profilePic, { marginTop: 40 }]}
                            />
                            <Text style={[styles.name, { color: "white" }]}>{nama}</Text>
                            <Text style={[styles.jobTitle, { color: "white" }]}>{email}</Text>
                        </View>
                        <View style={[{ paddingHorizontal: 20, paddingVertical: 5, backgroundColor: 'white' }]}>
                            <Contact data={contact}></Contact>
                        </View>
                        {/* <Produk data={produk} /> */}
                        {/* <View style={{ minHeight: 100, marginTop: 10, padding: 20, backgroundColor: 'white' }}>
                            <ScrollView horizontal={true}>
                                <View style={{ marginHorizontal: 10, width: 50 }}>
                                    <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', width: 50, borderRadius: 25, height: 50, backgroundColor: config.color.primary }}>
                                        <Text style={{ fontSize: 20, color: 'white' }}>20</Text>
                                    </View>
                                    <Text style={{ textAlign: 'center' }}>Dos</Text>
                                </View>
                                <View style={{ marginHorizontal: 10, width: 50 }}>
                                    <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', width: 50, borderRadius: 25, height: 50, backgroundColor: config.color.primary }}>
                                        <Text style={{ fontSize: 20, color: 'white' }}>20</Text>
                                    </View>
                                    <Text style={{ textAlign: 'center' }}>Bal</Text>
                                </View>
                                <View style={{ marginHorizontal: 10, width: 50 }}>
                                    <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', width: 50, borderRadius: 25, height: 50, backgroundColor: config.color.primary }}>
                                        <Text style={{ fontSize: 20, color: 'white' }}>20</Text>
                                    </View>
                                    <Text style={{ textAlign: 'center' }}>Slop</Text>
                                </View>
                            </ScrollView>
                        </View> */}
                    </View>
                </ScrollView>
                <View style={{
                    position: 'absolute',
                    height: heightWIndow,
                    zIndex: 1,
                    bottom: 0,
                    left: 0,
                    display: formArea === 'none' ? 'none' : 'flex', // Updated display logic
                    width: '100%',
                    shadowColor: '#000',
                    shadowRadius: 10,
                    shadowOffset: { width: 0, height: 20 },
                    shadowOpacity: 1,
                    borderTopWidth: 2,
                    borderColor: "#ddd"
                }}>
                    <View style={{ backgroundColor: 'rgba(0,0,0,0.3)', flex: 1 }}>

                    </View>
                    <View style={{ backgroundColor: 'white', height: 160, paddingVertical: 16 }}>
                        <Text style={{ paddingHorizontal: 20, fontSize: 16, margin: 0, paddingVertical: 5, marginBottom: 10 }}>{formTitle}</Text>
                        <TextInput ref={inputRef} onChangeText={setInputVal} value={inputVal} placeholder='...' style={{ height: 40, backgroundColor: '#ddd', marginHorizontal: 20, paddingHorizontal: 10, borderRadius: 4 }} keyboardType="default" />
                        <View style={{ flexDirection: 'row', paddingHorizontal: 20 }}>
                            {formName != 'country_id' && formName != 'company_id' ?
                                <TouchableOpacity onPress={async () => {
                                    let data: any = JSON.parse(atob(Act));
                                    data[formName] = inputVal;
                                    let g = btoa(JSON.stringify(data));
                                    setAct(g)
                                    callData(g)
                                    setFormArea('none')
                                    await DB(`UPDATE res_partner SET ${formName} = '${inputVal}' WHERE id = ${Id}`)
                                    await addStorage('contactActiveData', data);
                                    Keyboard.dismiss()
                                    act()
                                }}>
                                    <View style={{ padding: 10 }}>
                                        <Text style={{ color: config.color.primary }}>Simpan</Text>
                                    </View>
                                </TouchableOpacity>
                                : <></>
                            }
                            <TouchableOpacity onPress={() => {
                                Keyboard.dismiss()
                                setFormArea('none')
                            }}>
                                <View style={{ padding: 10 }}>
                                    <Text style={{ color: config.color.primary }}>Tutup</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </GestureHandlerRootView>
        </>
    );
};


export default CustDetail;