import React, { Fragment, useState, useEffect, useCallback, createRef, useRef } from 'react';
import { View, Text, Alert, FlatList, StyleSheet, TouchableOpacity } from 'react-native';
import Styled from 'styled-components/native';
import Header from '~/Components/Layouts/Header';
import { Search, SearchIcon, Line, TextInput, checkFilter, filterValue, ListStyle, DetailIcon, RightArrow, CreateButton } from '~/Components/Listing/Search';
import Checkbox from '~/Components/UIControls/Checkbox';
import Theme from '~/Themes';
import BottomTabBarLayout from '~/Components/Layouts/BottomTabBarLayout';
import session from '~/Utils/session';
import SearchList, { SearchListContainer } from '~/Components/Listing/SearchList';
import EmptyView from '~/Components/Listing/EmptyView';
import EntitySelect from '~/Components/EntitySelect';
import { useToast } from '~/Components/UIControls/Message';
import { DateTimePicker } from '~/Components/UIControls/DateTimePicker';
import Input from '~/Components/UIControls/Input';
import Form from '~/Components/Form';
import { Util } from '~/Utils/utils';
import { useAuth } from '~/Components/Hooks';
import Icon from '~/Components/UIControls/Icon';
import { fetchDelete, fetchGet } from '~/Utils/fetch';

// list item
const Item = ({item, index, onPress=()=>{}, onUp=(item)=>{}, onDown=(item)=>{}, onDelete=(item)=>{}}) => {
    const zebra = index % 2 == 0 ? true : false;
    const ShortcutIcon = Util.svg(item.Icon);
    return (
        <TouchableOpacity onPress={onPress} style={{
            ...ListStyle.itemContainer, 
            borderTopWidth: 0, 
            backgroundColor: (zebra?'#fdfdfd':'#fff'),
        }}>
            <View style={{...ListStyle.vertical, flex:1}}>
                <View style={{...ListStyle.horizon}}>
                    {ShortcutIcon != null ? (
                        <ShortcutIcon width={40} height={40} style={{marginRight:10}} />
                    ) : (
                        <View style={{width:40, height:40}} style={{marginRight:10}} />
                    )}
                    <Text style={[ListStyle.text]} >{Util.get(item, "Sitemap.Name")}</Text>
                </View>
            </View>
            <View style={[ListStyle.horizon, ListStyle.fillRounded, {paddingLeft:5, paddingRight:5, height:40, borderRadius:20, marginRight:10, backgroundColor:'#9aa3ac'}]}>
                <TouchableOpacity onPress={() => {onUp(item)}}>
                    <Icon iconFamily="Entypo" iconName="chevron-small-up" color="white" size={40} />
                </TouchableOpacity>
                <TouchableOpacity onPress={() => {onDown(item)}}>
                    <Icon iconFamily="Entypo" iconName="chevron-small-down" color="white" size={40} />
                </TouchableOpacity>
            </View>
            <TouchableOpacity onPress={() => {onDelete(item)}} style={{marginRight:15}}>
                <Icon iconFamily="AntDesign" iconName="closecircle" color="#9aa3ac" size={40} />
            </TouchableOpacity>
        </TouchableOpacity>
    )
}

// list and search
const Screen = (props) => {
    const navigation = props.navigation;
    const [list, setList] = useState(null);
    const [page, setPage] = useState(1);
    const [refreshing, setRefreshing] = useState(false);
    const { auth, userinfo } = useAuth(navigation);
    const tabBarLayoutRef = useRef();
    const { showMessage } = useToast();

    // search events...
    const start = () => {
        setRefreshing(true);
    }
    const success = (data, append) => {
        console.log("success : ", data);
        setList(data);
        setRefreshing(false);
    }
    const fail = (e) => {
        showMessage(e.message);
        setRefreshing(false);
    }

    const refreshList = () => {
        setPage('refresh-' + Math.random());
        tabBarLayoutRef.current.fetchShortcuts();
    }

    const positionUp = async (item) => {
        setRefreshing(true);
        try {
            await fetchGet(`api/app/MobileShortcut/PositionUp?userId=${userinfo.UserId}&sitemapId=${item.SitemapId}&type=${item.Type}`);
            tabBarLayoutRef.current.fetchShortcuts();
        } catch(error) {
            showMessage(error.message);
        }
        refreshList();
    }

    const positionDown = async (item) => {
        setRefreshing(true);
        try {
            await fetchGet(`api/app/MobileShortcut/PositionDown?userId=${userinfo.UserId}&sitemapId=${item.SitemapId}&type=${item.Type}`);
            tabBarLayoutRef.current.fetchShortcuts();
        } catch(error) {
            showMessage(error.message);
        }
        refreshList();
    }

    const deleteItem = async (item) => {
        setRefreshing(true);
        try {
            await fetchDelete(`api/app/MobileShortcut/${userinfo.UserId}/${item.SitemapId}/${item.Type}`);
            tabBarLayoutRef.current.fetchShortcuts();
        } catch(error) {
            showMessage(error.message);
        }
        refreshList();
    }

    return (
        <BottomTabBarLayout ref={tabBarLayoutRef}>
            <SearchListContainer>
                <SearchList data={list} refreshing={refreshing} page={page} pages={1} setPage={setPage}
                    renderItem={({ item, index }) => {
                        return (
                            <Item item={item} index={index} onPress={() => {
                                navigation.navigate('Form', {
                                    refreshList: refreshList,
                                    action: Form.VIEW, 
                                    shortcutId: item.MobileShortcutId,
                                    auth: auth,
                                    userinfo: userinfo,
                                });
                            }} onUp={(item) => {
                                positionUp(item);
                            }} onDown={(item) => {
                                positionDown(item);
                            }} onDelete={(item) => {
                                deleteItem(item);
                            }} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
                {auth.Update && (<CreateButton onPress={() => {
                    navigation.navigate('Form', {
                        refreshList: refreshList,
                        action: Form.CREATE, 
                        shortcutId: 0,
                        auth: auth,
                        userinfo: userinfo,
                    });
                }} />)}
            </SearchListContainer>

            <Search id="bottom-shortcut-search" api={`api/app/MobileShortcut/BottomList?userId=${userinfo.UserId}`} 
                page={page} setPage={setPage}
                onStart={start} onSuccess={success} onFailure={fail} />
        </BottomTabBarLayout> 
    );
};

// header
Screen.navigationOptions = ({navigation}) => { 
    return { 
        header: () => <Header 
            navigation={navigation} 
            title="단축메뉴" 
        /> 
    } 
};

export default Screen;