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, SearchTitle, FileTextIcon } 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 = () => { } }) => {
    //console.log(item);
    const zebra = index % 2 === 0 ? true : false;
    const boxColor = zebra === true ? "#0b83e6":"#0eb118";
    return (
        <TouchableOpacity onPress={onPress} style={{ ...ListStyle.itemContainer, borderTopWidth: 0, backgroundColor: zebra ? "#fdfdfd" : "#fff" }}>
            <View style={{...ListStyle.horizon,flex:1}}>
                <View style={{ ...ListStyle.vertical, flex:1}}>
                    <View style={{ ...ListStyle.horizon}}>
                        <Text style={{...ListStyle.rounded}}>{Util.get(item, "Investigation3GroupName")}</Text>
                        <Text>&nbsp;&nbsp;</Text>
                        <Text style={{...ListStyle.rounded}}>{Util.get(item, "Investigation3TypeName")}</Text>
                        <Text>&nbsp;&nbsp;</Text>
                        <Text style={{...ListStyle.textLightGray}}>{Util.get(item, "InvestigationNo")}</Text>
                    </View>
                    <View style={{ ...ListStyle.horizon, marginTop:5}}>
                        <Text style={{ ...ListStyle.text, borderColor: boxColor }}>
                        {Util.get(item, "Name")}
                        </Text>
                    </View>          
                </View>
                <View style={{...ListStyle.horizon,paddingRight:15}}>
                    <FileTextIcon />
                </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();

    // load session when mount...
    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, 
                                    investigationId: item.InvestigationId, 
                                    auth: auth,
                                    userinfo: userinfo,
                                });
                            }} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
                {auth.Update && (
                    <CreateButton onPress={() => {
                        navigation.navigate('Form', {
                            refreshList: refreshList,
                            action: Form.CREATE, 
                            siteId: userinfo.SiteId, 
                            investigationId: 0, 
                            auth: auth,
                            userinfo: userinfo,
                        });
                    }} />
                )}
            </SearchListContainer>

            <Search id="investigation3" api={`api/investigation3?siteId=${userinfo.SiteId}`} 
                    page={page} setPage={setPage} limit={50} filters={filters} sort={{field:'DrawingId', order:'desc'}}
                    onStart={start} onSuccess={success} onFailure={fail} >
                <Fragment>
                    <SearchTitle title="분류" />
                    <EntitySelect style={{ marginBottom:20 }} entity="CmInvestigation3CodeGroup" defaultLabel="분류" emptyLabel="전체" 
                        id="InvestigationGroupId" name="Name" useCheck={true}
                        onChange={(item) => { filterValue([filters, setFilters], 'InvestigationGroupId', item.value, 'eq') }} />

                    <SearchTitle title="유형" />
                    <EntitySelect style={{ marginBottom:20 }} entity="CmInvestigation3CodeType" defaultLabel="유형" emptyLabel="전체" 
                        id="InvestigationTypeId" name="Name" useCheck={true}
                        onChange={(item) => { filterValue([filters, setFilters], 'InvestigationTypeId', item.value, 'eq') }} />

                    <SearchTitle title="이름" />
                    <Input style={{ marginBottom:20 }} placeholder="이름" small onChangeText={value => filterValue([filters, setFilters], 'Name', value, 'cn')} />

                    <SearchTitle title="본사등록" />
                    <Selectbox style={{ marginBottom:20 }} defaultLabel="본사등록" emptyLabel="전체"
                        items={[{label:'예', value:true}, {label:'아니오', value:false}]}
                        onChange={item => {
                            filterValue([filters, setFilters], 'IsAllSite', item.value, 'eq');
                        }} />

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

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

export default Screen;