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

// 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'),
        }}>
            <View style={{...ListStyle.vertical, flex:1}}>
                <View style={{...ListStyle.horizon, marginBottom:8}}>
                    <Text style={{...ListStyle.rounded}}>{Util.get(item, "StateTypeName")}</Text>
                </View>
                <Text style={{...ListStyle.textMedium}}>
                    {Util.get(item, "Title")}
                </Text>
                <View style={{...ListStyle.horizon, width:'100%', paddingRight:15, justifyContent:'space-between'}}>
                    <Text style={{...ListStyle.textLightGray}}>시작일</Text>
                    <Text style={{...ListStyle.textLightGray}}>{Util.getDateString(item, "StartDate")}</Text>
                </View>
                <View style={{...ListStyle.horizon, width:'100%', paddingRight:15, justifyContent:'space-between'}}>
                    <Text style={{...ListStyle.textLightGray}}>종료일</Text>
                    <Text style={{...ListStyle.textLightGray}}>{Util.getDateString(item, "EndDate")}</Text>
                </View>
            </View>
        </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 pages = useRef(10);
    const { auth, userinfo } = useAuth(navigation);
    const { showMessage } = useToast();

    useEffect(() => {
    }, []);

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

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

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

    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', {
                                    refreshList: refreshList,
                                    action: Form.VIEW, 
                                    siteId: userinfo.SiteId, 
                                    facilityStateId: item.FacilityStateId, 
                                    auth: auth,
                                });
                            }} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            </SearchListContainer>

            <Search id="facility-state-search" api={`api/FacilityState?siteId=${userinfo.SiteId}`} 
                    page={page} setPage={setPage} limit={50} filters={filters} sort={{field:'FacilityStateId', order:'desc'}}
                    onStart={start} onSuccess={success} onFailure={fail} onAction={(action)=>{ onAction(action) }}>
                <Fragment>
                    <SearchTitle title="진행상태" />
                    <Selectbox  
                        style={{ marginBottom:20 }}
                        defaultLabel="진행상태" 
                        emptyLabel="전체" 
                        items={[
                            {label:'준비중', value:'1'},
                            {label:'진행중', value:'2'},
                            {label:'완료', value:'3'},
                        ]} 
                        onChange={(item) => {
                            filterValue([filters, setFilters], 'StateType', item.value, 'eq');
                        }}
                    />

                    <SearchTitle title="질문제목" />
                    <Input style={{ marginBottom:20 }} placeholder="질문제목" small onChangeText={value => filterValue([filters, setFilters], 'Title', value, 'cn')} />

                    <SearchTitle title="기간검색" />
                    <DateTimePicker style={{ marginBottom:5 }} placeholder="시작일" useClear={true} onChange={(newDate) => {
                        filterValue([filters, setFilters], 'StartDate', Util.toDateString(newDate), 'ge');
                    }} />
                    <DateTimePicker style={{ marginBottom:20 }} placeholder="종료일" useClear={true} onChange={(newDate) => {
                        filterValue([filters, setFilters], 'EndDate', Util.toDateString(newDate), 'le');
                    }} />

                </Fragment>
            </Search>
        </BottomTabBarLayout> 
    );
};

// header
Screen.navigationOptions = ({navigation}) => { 
    const Buttons = ({navigation}) => {
        const { action } = useSearch('facility-state-search');

        return (
            <Fragment>
                <SearchIcon id="facility-state-search" />
            </Fragment>
        )
    }

    return { 
        header: () => <Header 
            navigation={navigation} 
            title="정보조사(설문)" 
            buttons={<Buttons navigation={navigation} />}
        /> 
    } 
};

export default Screen;