import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, Keyboard, TouchableWithoutFeedback, Modal, Pressable, ScrollView } from 'react-native';
import { useFocusEffect } from '@react-navigation/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';

const DetailItem = ({ item }) => {
    return (
        <>
            <View style={{
                flexDirection: "row", padding: "5%", borderColor: '#d3d3d3', //light grey
                borderWidth: 1, borderTopWidth: 0,
            }}>
                <Text style={[style.itemText, item.type === 1 ? style.inputColor : style.outputColor]}>{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>
        </>
    );
};

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

function MainScreen({ navigation }) {
    const day = new Date(getDateStr())
    const daysToSubtract = day.getDay()
    const startingDate = new Date(day.getFullYear(), day.getMonth(), day.getDate() - daysToSubtract)
    const endDate = 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 [weeklyData, setWeeklyData] = useState([])
    const [weekMoney, setWeekMoney] = useState({ input: 0, output: 0 })

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

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

    useFocusEffect(
        React.useCallback(() => {
            getWeeklyData(startingDate, endDate)
            getTotalMoney()
        }, [])
    );

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

    const getWeeklyData = async (start, end) => {
        const { data, input, output } = await weekApi.getWeeklyData(start, end)
        setWeeklyData(data)
        setWeekMoney({ input: input, output, output })
    }

    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))}
                        weeklyData={weeklyData}
                    />
                    <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} />)}
                                        </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={{ name: 'add', color: '#fff' }}
                            title="부채"
                            onPress={() => navigation.navigate('DeptPage')}
                        />
                        <SpeedDial.Action
                            icon={{ name: 'add', 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: "#6b768a",
        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'
    },
    itemTextNum: {
        flex: 1,
        textAlign: "center",
    },
    itemText: {
        flex: 1,
    },
    submitButton: {
        backgroundColor: "#6b768a",
        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;