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, SearchTitle } 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 { Util } from '~/Utils/utils';
import { useAuth } from '~/Components/Hooks';

// list item
const Item = ({item, index, onPress=()=>{}}) => {
    const zebra = index % 2 == 0 ? true : false;
    return (
        <TouchableOpacity onPress={onPress} style={{
            ...ListStyle.itemContainer, 
            borderTopWidth: 0, 
            backgroundColor: (zebra?'#fdfdfd':'#fff'),
        }}>
            <Text style={{
                ...ListStyle.text, 
                paddingLeft:20, flex:1
            }}>{Util.get(item, "Name")}</Text>
            <DetailIcon />
        </TouchableOpacity>
    )
}

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

    // load session when mount...
    useEffect(() => {
    }, []);

    // search events...
    const start = () => {
        setRefreshing(true);
    }
    const success = (data, append) => {
        pages.current = data.pages;

        if(append && page > 1) {
            setList(list.concat(data.list));
        } else {
            setList(data.list);
        }
        setRefreshing(false);
    }
    const fail = (e) => {
        showMessage(e.message);
        setRefreshing(false);
    }

    return (
        <BottomTabBarLayout>
            <SearchListContainer>
                <SearchList page={page} pages={pages.current} setPage={setPage} refreshing={refreshing}
                    data={list} renderItem={({ item, index }) => {
                        return (
                            <Item item={item} index={index} onPress={() => {
                                navigation.navigate('Form', {
                                    action:'view', 
                                    siteId:userinfo.SiteId, 
                                    buildingId:item.BuildingId, 
                                    floorId: item.FloorId,
                                    auth: auth,
                                    userinfo: userinfo,
                                });
                            }} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            </SearchListContainer>

            <Search id="floor" api={`api/app/Floor?siteId=${userinfo.SiteId}`} 
                    page={page} setPage={setPage} limit={50} filters={filters} sort={{field:'FloorId', order:'desc'}}
                    onStart={start} onSuccess={success} onFailure={fail} >
                <Fragment>
                    <SearchTitle title="빌딩" />
                    <EntitySelect style={{ marginBottom:20 }} entity="CmBuilding" siteId={userinfo.SiteId} defaultLabel="빌딩" emptyLabel="전체" 
                        onChange={(item) => { filterValue([filters, setFilters], 'BuildingId', item.value, 'eq')}} />

                    <SearchTitle title="층명" />
                    <Input style={{ marginBottom:20 }} placeholder="층명" small onChangeText={value => filterValue([filters, setFilters], 'Name', value, 'cn')} />
                </Fragment>
            </Search>
        </BottomTabBarLayout> 
    );
};

// header
Screen.navigationOptions = ({navigation}) => { 
    return { 
        header: () => <Header
            navigation={navigation} 
            title="층정보" 
            buttons={<SearchIcon id="floor" />}
        /> 
    } 
};

export default Screen;