import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, Keyboard, TouchableWithoutFeedback, TouchableOpacity, Modal, Pressable, ScrollView } from 'react-native';
import { SpeedDial } from 'react-native-elements';
import WeeklyCalendar from './components/WeeklyCalendar';
import Ionicons from 'react-native-vector-icons/Ionicons';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import DeptPage from './DeptPage';
import weekApi from './db/mainScreen.api';
import { getDateStr } from './utils/dateFunction';
import { useIsFocused } from '@react-navigation/native';

const DetailItem = ({ item, onPress }) => {
    let item_color
    switch (item.type) {
        case 1:
            item_color = style.inputColor;
            break;
        case 2:
            item_color = style.outputColor;
            break;
        case 3:
            item_color = style.moveColor;
            break;
    }
    return (
        <TouchableOpacity onPress={onPress}>
            <View style={{
                padding: "5%", borderColor: '#d3d3d3', //light grey
                borderWidth: 1, borderTopWidth: 0,
            }}>
                <View style={{ flexDirection: "row" }}>
                    <Text style={[style.itemText, item_color]}>{item.category}</Text>
                    <Text style={[style.itemTextNum, style.Font]}>{item.contents}</Text>
                    <Text style={[style.itemTextNum, style.Font]}>{(item.price).toLocaleString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}원</Text>
                </View>
                {item.asset ?
                    <Text style={[style.itemTextNum, style.Font]}>
                        {'(' + item.asset + '>' + item.deposit_asset + ')'}
                    </Text>
                    : null}
            </View>
        </TouchableOpacity>
    );
};

const AssetItem = ({ item }) => {
    return (
        <View style={{ flexDirection: "row", width: 180 }}>
            <Text style={[style.Font, { width: "40%", textAlign: 'left' }]}>{item.name}</Text>
            <Text style={[style.Font, { width: "60%", textAlign: 'right' }]}>{(item.price).toLocaleString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")} 원</Text>
        </View>
    );
};

const getMarkedDates = (weeklyData) => {
    if (weeklyData.length === 0) {
        return ([]);
    }

    const markedData = weeklyData.map(data => {
        return (
            {
                date: data.date,
                dots: getDots(data.type_id)
            }
        );
    })
    return (markedData)
}

const getDots = (typeArray) => {
    const tempDots = []
    for (let i = 0; i < typeArray.length; i++) {
        if (typeArray[i] === "1") {
            tempDots.push({ color: "#7192d1" })
        } else if (typeArray[i] === '2') {
            tempDots.push({ color: "#d98b79" })
        } else {
            tempDots.push({ color: "white" })
        }
    }
    return tempDots;
}

function MainScreen({ navigation }) {
    const isFocused = useIsFocused();

    const day = new Date(getDateStr())
    const daysToSubtract = day.getDay()
    const initialStartingDate = new Date(day.getFullYear(), day.getMonth(), day.getDate() - daysToSubtract)
    const initialEndDate = new Date(day.getFullYear(), day.getMonth(), day.getDate() + (6 - daysToSubtract))

    const [modalOpen, setModalOpen] = useState(false);
    const [open, setOpen] = useState(false)

    const [selectedDate, setSelectedDate] = useState(getDateStr())
    const [startingDate, setStartingDate] = useState(initialStartingDate)
    const [weekMoney, setWeekMoney] = useState({ input: 0, output: 0 })
    const [markedDates, setMarkedDates] = useState([])

    const [singleMoney, setSingleMoney] = useState([])

    const [totalMoney, setTotalMoney] = useState(0)
    const [totalAssetsMoney, setTotalAssetsMoney] = useState([])

    useEffect(() => {
        getthisWeekData(initialStartingDate, initialEndDate);
        getTotalMoney();
        getSingleData();
    }, [isFocused])

    const getthisWeekData = async (start, end) => {
        const { data, input, output } = await weekApi.getWeeklyData(start, end)
        setStartingDate(start)
        setWeekMoney({ input: input, output, output })
        setTimeout(() => {
            setMarkedDates(getMarkedDates(data))
        }, 300)
    }

    const getWeeklyData = async (start, end) => {
        if (getDateStr(start) !== getDateStr(startingDate)) {
            const { data, input, output } = await weekApi.getWeeklyData(start, end)
            setStartingDate(start)
            setWeekMoney({ input: input, output, output })
            setMarkedDates(getMarkedDates(data))
        }
    }

    const getTotalMoney = async () => {
        const { total, assets_total } = await weekApi.getTotalData()
        setTotalMoney(total)
        setTotalAssetsMoney(assets_total)
    }

    useEffect(() => {
        getSingleData()
    }, [selectedDate])

    const getSingleData = async () => {
        const tempData = await weekApi.getData(selectedDate)
        setSingleMoney(tempData)
    }

    return (
        <>
            <TouchableWithoutFeedback onPress={() => {
                Keyboard.dismiss();
            }}>
                <View style={{ flex: 1 }}>
                    <WeeklyCalendar
                        selectedDate={selectedDate}
                        startingDate={startingDate}
                        onWeekChanged={(start, end) => getWeeklyData(start, end)}
                        onDateSelected={(date) => setSelectedDate(getDateStr(date))}
                        markedDates={markedDates}
                    />
                    <View style={style.weekData}>
                        <Text style={[style.Font, { color: 'white' }]}>수입 {weekMoney.input}</Text>
                        <Text style={[style.Font, { color: 'white' }]}>지출 {weekMoney.output}</Text>
                    </View>
                    <ScrollView nestedScrollEnabled={true} horizontal={false} >
                        <>
                            <View>
                                {
                                    singleMoney.length !== 0 ?
                                        <View>
                                            {singleMoney.length !== 0 && singleMoney.map((item, index) => <DetailItem item={item} key={index} onPress={() => navigation.navigate('UpdatePage', [selectedDate, item])} />)}
                                        </View>
                                        : <View style={{ marginTop: 10, marginBottom: 50 }}>
                                            <Text style={{ textAlign: "center", fontSize: 20, fontFamily: 'GowunDodum-Regular' }}>내역이 없습니다.</Text>
                                        </View>
                                }
                            </View>
                            <View style={style.Contents}>
                                <Text style={[style.Font, { fontWeight: 'bold' }]}>총 자산</Text>
                                <Text style={style.totalMoney}><FontAwesome name="won" style={style.totalMoney} /> {(totalMoney).toLocaleString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}</Text>
                                <View style={{ marginTop: 5 }}>
                                    {totalAssetsMoney.length !== 0 && totalAssetsMoney.map((item, index) => <AssetItem item={item} key={index} />)}
                                </View>
                            </View>
                            <Pressable
                                onPress={() => navigation.navigate('PostMoney')}
                                style={style.submitButton}
                            >
                                <Text style={[style.Font, { color: 'white' }]}>수입/지출 기록</Text>
                            </Pressable>
                        </>
                    </ScrollView>
                    <SpeedDial
                        isOpen={open}
                        icon={{ name: 'edit', color: '#fff' }}
                        openIcon={{ name: 'close', color: '#fff' }}
                        onOpen={() => setOpen(!open)}
                        onClose={() => setOpen(!open)}
                    >
                        <SpeedDial.Action
                            icon={<FontAwesome name={'money'} size={20} color={'#fff'} />}
                            title="부채"
                            onPress={() => navigation.navigate('DeptPage')}
                        />
                        <SpeedDial.Action
                            icon={{ name: 'note', color: '#fff' }}
                            title="메모"
                            onPress={() => navigation.navigate('MemoPage')}
                        />

                    </SpeedDial>
                    <Modal visible={modalOpen} animationType='slide'>
                        <View style={style.modalContent}>
                            <Ionicons
                                name='close'
                                color='red'
                                size={24}
                                style={{ ...style.modalToggle, ...style.modalClose }}
                                onPress={() => setModalOpen(false)}
                            />
                            <DeptPage />
                        </View>
                    </Modal>

                </View>
            </TouchableWithoutFeedback>
        </>
    )
}

const style = StyleSheet.create({
    weekData: {
        flexDirection: "row",
        justifyContent: "space-around",
        backgroundColor: "#adbfdb",
        paddingBottom: 10,
    },
    TextInput: {
        borderColor: 'skyblue',
        height: 40,
        margin: 12,
        borderWidth: 1
    },
    totalMoney: {
        fontSize: 35,
    },
    Font: {
        fontFamily: 'GowunDodum-Regular',
        fontSize: 18
    },
    inputColor: {
        color: '#1E90FF'
    },
    outputColor: {
        color: '#dc143c'
    },
    moveColor: {
        color: '#646d75'
    },
    itemTextNum: {
        flex: 1,
        textAlign: "center",
    },
    itemText: {
        flex: 1,
    },
    submitButton: {
        backgroundColor: '#bfd3f2',
        margin: 10,
        height: 50,
        alignItems: 'center',
        justifyContent: 'center',
    },
    modalToggle: {

        padding: 10,
        borderRadius: 10,
        alignSelf: 'flex-start',
        marginTop: -40, //위치를 center로
    },
    modalClose: {
        alignSelf: 'center',
        alignItems: 'flex-start',
        marginTop: 150,
        marginBottom: 50,
    },
    modalContent: {
        flex: 1,
    },
    Contents: {
        alignItems: "center",
        margin: 20
    }
});

export default MainScreen;