import React, { useEffect, useRef, useState } from 'react';
import { ScrollView, View, Text, Image, TouchableOpacity, BackHandler, Dimensions, ImageBackground } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import config from '../../components/data/config.json'
import { styles } from '@/components/style/style';
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 { cfg, getStorage } from '@/components/lib/cfg';
import { DB } from '@/components/lib/db';
import DetailOrder from '@/components/pageComponent/detailOrder';

const formatNumber = function (number: any) {
    return number.toLocaleString('id-ID', {
        minimumFractionDigits: 0,
        maximumFractionDigits: 0
    });
}


function formatDate(dateString: any) {
    const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

    // Parse the date string
    const date = new Date(dateString);

    // Extract year, month, and date
    const year = date.getFullYear();
    const month = months[date.getMonth()];
    const day = String(date.getDate()).padStart(2, '0');

    // Format the date string
    const formattedDate = `${day} ${month} ${year}`;

    // Return the object with the desired structure
    return {
        bulan: month,
        tanggal: day,
        tahun: year,
        date: formattedDate
    };
}

const Contact = ({ data: mapOfData, setDataOrder, setDataOrderList, setShowDetail }: any) => {
    return (
        <>
            {(Array.isArray(mapOfData) ? mapOfData : []).map((data: any, key: number) =>
                <TouchableOpacity key={key}>
                    <View style={{
                        paddingLeft: 10,
                        backgroundColor: "green",
                        marginBottom: 10,
                        overflow: 'hidden',
                        borderRadius: 5
                    }}>
                        <View style={[
                            { padding: 10, backgroundColor: 'white' }
                            , { flexDirection: "row", alignItems: "center" }
                        ]}>
                            <View style={[{ flexDirection: "row" }, { flex: 1 }]}>
                                <View style={{ width: 38 }}>
                                    <Text style={{
                                        fontSize: 14
                                        , textAlign: 'center'
                                        , fontWeight: 'bold'
                                    }}>{formatDate(data?.payment_date).bulan}</Text>
                                    <Text style={{
                                        fontSize: 24
                                        , textAlign: 'center'
                                        , fontWeight: '900'
                                    }}>{formatDate(data?.payment_date).tanggal}</Text>
                                    <Text style={{
                                        fontSize: 14
                                        , textAlign: 'center'
                                        , fontWeight: 'bold'
                                    }}>{formatDate(data?.payment_date).tahun}</Text>
                                </View>
                                <View style={{ paddingHorizontal: 10, flexDirection: 'column' }}>
                                    <Text ellipsizeMode='tail' style={[{
                                        flex: 1
                                        , fontWeight: '700'
                                        , fontSize: 16
                                    }]}>
                                        Invoice : {data?.payment_reference}
                                    </Text>
                                    <Text ellipsizeMode='tail' style={[{
                                        flex: 1
                                        , fontWeight: '700'
                                        , fontSize: 18
                                    }]}>
                                        {data?.nama_user}
                                    </Text>
                                    <Text ellipsizeMode='tail' style={[{
                                        flex: 1,
                                        color: 'red',
                                        fontWeight: 'bold'
                                        , fontSize: 18
                                    }]}> 
                                        Rp {formatNumber(Number(data?.total_pembayaran))}
                                    </Text>
                                </View>
                            </View>
                            <View style={{ width: 120, flexDirection: 'column' }}>
                                <View style={{ height: '100%', flex: 1 }}>
                                    <Text style={{ textAlign: 'right', fontSize: 12, fontWeight: '800' }}>Tanggal Dibuat</Text>
                                    <Text style={{ textAlign: 'right', fontSize: 14, fontWeight: '800' }}>{formatDate(data?.payment_date).date}</Text>
                                    <Text style={{ color: 'red', marginTop: 10, textAlign: 'right', fontSize: 18, fontWeight: '800' }}>{data?.lunas ? 'Lunas' :`Parsial`}</Text>
                                </View>
                            </View>
                        </View>
                    </View>
                </TouchableOpacity>
            )}
        </>
    )
}

const OrderLunasSreen = () => {
    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<any>([]);
    const [salesTotal, setSalesTotal] = useState(0);
    const [salesTotal2, setSalesTotal2] = useState(0);
    const [showDetail, setShowDetail] = useState(false);
    const [dataOrder, setDataOrder] = useState<any>({});
    const [dataForm, setDataForm] = useState(false);
    const [dataOrderList, setDataOrderList] = useState<any>([])
    const [produk, setProduk] = useState<{
        name: string
        , value: string
    }[]>([]);

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


    useFocusEffect(
        React.useCallback(() => {

            const onBackPress = () => {
                if (showDetail === true) {
                    setShowDetail(false)
                } else {
                    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, showDetail, setShowDetail])
    );



    const callData = async () => {
        let data : any = await AsyncStorage.getItem('login');
        data = JSON.parse(data);
        data = data.length > 0 ? data[0] : {};
        let sales: any = await DB(`
            SELECT * FROM view_sales_payment_status 
        `);
        let [salesLunas]: any = await DB(`
            SELECT count(*) total FROM view_sales_payment_status_lunas 
        `);
        let [salesPasial]: any = await DB(`
            SELECT count(*) total FROM view_sales_payment_status_parsial
        `);

        setSalesTotal(Number(salesLunas?.total))
        setSalesTotal2(Number(salesPasial?.total))

        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(sales);
    };

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

    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 (
        <>
            {
                showDetail === true ?
                    <DetailOrder order={dataOrder} orderlist={dataOrderList} config={config} act={setShowDetail} />
                    : <>
                        {dataForm? <>
                            <View>

                            </View>
                        </>:<>
                            <GestureHandlerRootView>
                                <ScrollView onScroll={onScroll}>
                                    <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>
                                    <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: 70, 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={{ position: "static", top: -80 }}>
                                            <View style={{ paddingHorizontal: 20, paddingVertical: 10 }}>
                                                <View style={{
                                                    backgroundColor: "orange"
                                                    , padding: 10
                                                    , paddingVertical: 20
                                                    , borderRadius: 15
                                                    , flexDirection: 'row'
                                                }}>
                                                    <View style={{ flex: 1 }}>
                                                        <Text style={{
                                                            fontSize: 12
                                                            , color: '#000'
                                                            , fontWeight: '600'
                                                            , textAlign: 'center'
                                                        }}>{(`total\nPelunasan Lunas`).toUpperCase()}</Text>
                                                        <Text style={{
                                                            fontSize: 28
                                                            , color: '#000'
                                                            , fontWeight: 'bold'
                                                            , textAlign: 'center'
                                                        }}>{salesTotal}</Text>
                                                    </View>
                                                    <View style={{ flex: 1 }}>
                                                        <Text style={{
                                                            fontSize: 12
                                                            , color: '#000'
                                                            , fontWeight: '600'
                                                            , textAlign: 'center'
                                                        }}>{(`total\nPelunasan Parsial`).toUpperCase()}</Text>
                                                        <Text style={{
                                                            fontSize: 28
                                                            , color: '#000'
                                                            , fontWeight: 'bold'
                                                            , textAlign: 'center'
                                                        }}>{salesTotal2}</Text>
                                                    </View>
                                                </View>
                                            </View>
                                            <View style={{ marginVertical: 10, flexDirection: "row", paddingHorizontal: 20 }}>
                                                <TextInput style={{
                                                    flex: 1,
                                                    backgroundColor: "white",
                                                    height: 40,
                                                    paddingHorizontal: 10,
                                                    borderColor: "#333",
                                                    borderWidth: 1,
                                                    borderRadius: 4
                                                }} placeholder={`search`}></TextInput>
                                                <View style={{
                                                    width: 50
                                                    , height: 40
                                                    , marginLeft: 10
                                                    , flexDirection: "row"
                                                    , justifyContent: "center"
                                                    , alignItems: "center"
                                                    , backgroundColor: "gray"
                                                }}>
                                                    <Image
                                                        source={require('../../assets/images/icons/filter.png')}
                                                        style={{ width: 20, height: 20 }}
                                                    />
                                                </View>
                                            </View>
                                            <View style={[{ paddingHorizontal: 20, paddingVertical: 5 }]}>
                                                <Text style={{ fontSize: 24, textAlign: 'center', fontWeight: '600' }}>List Order Lunas</Text>
                                            </View>
                                            <View style={[{ paddingHorizontal: 20, paddingVertical: 5 }]}>
                                                <Contact setForm={setDataForm} setShowDetail={setShowDetail} setDataOrderList={setDataOrderList} setDataOrder={setDataOrder} data={contact}></Contact>
                                            </View>
                                        </View>
                                    </View>
                                </ScrollView>
                            </GestureHandlerRootView>
                        </>}
                    </>
            }
        </>
    );
};


export default OrderLunasSreen;