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 } 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';
// list item
const Item = ({item, index, onPress=()=>{}}) => {
    console.log(item);
    const zebra = index % 2 == 0 ? true : false;
    
    return (
        <TouchableOpacity onPress={onPress} style={{
            ...ListStyle.itemContainer, 
        }}>
            <View style={{...ListStyle.horizon, flex:1}}>
                <View style={{...ListStyle.vertical,paddingLeft:0, flex:1}}>
                    <View style={{...ListStyle.vertical,flex:1}}>
                        <View style={{...ListStyle.horizon}}>
                            <Text style={{...ListStyle.textMedium}}>{Util.get(item, "Name")}&nbsp;&nbsp;</Text>
                        </View>
                        <View style={{...ListStyle.horizon, width:'100%', justifyContent:'space-between', paddingRight:15}}>
                            <Text style={{ ...ListStyle.textGray }}>시작일</Text>
                            <Text style={{...ListStyle.textGray}}>{Util.get(item, "Dates.StartDate")}</Text>
                        </View>                        
                        <View style={{...ListStyle.horizon, width:'100%', justifyContent:'space-between', paddingRight:15}}>
                            <Text style={{ ...ListStyle.textGray }}>종료일</Text>
                            <Text style={{...ListStyle.textGray}}>{Util.get(item, "Dates.EndDate")}</Text>
                        </View>                        
                        <View style={{...ListStyle.horizon, width:'100%', justifyContent:'space-between', paddingRight:15}}>
                            <Text style={{ ...ListStyle.textGray }}>업체명</Text>
                            <Text style={{...ListStyle.textGray}}>{Util.get(item, "PartnerName")}</Text>
                        </View>                        
                    </View>
                </View>
            </View>
        </TouchableOpacity>
    )
}

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


    //console.log('filters : ', filters);

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

    // 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 (
        ready ? 
        <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: session.getSiteId(), 
                                    contractId: item.ContractId, 
                                    auth: auth,
                                });
                            }} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
                {auth.Update && <CreateButton onPress={() => {
                    navigation.navigate('Form', {
                        refreshList: refreshList,
                        action: Form.CREATE, 
                        siteId: session.getSiteId(), 
                        contractId : 0, 
                        auth: auth,
                    });
                }} />}
            </SearchListContainer>

            <Search id="contract" api={`api/app/ContractManagement?siteId=${session.getSiteId()}`} 
                    page={page} setPage={setPage} limit={50} filters={filters} sort={{field:'ContractId', order:'desc'}}
                    onStart={start} onSuccess={success} onFailure={fail} >
                <Fragment>
                    <SearchTitle title="기간검색" />
                    <DateTimePicker style={{ marginBottom:10 }} placeholder="시작일" useClear={true} onChange={(newDate) => {
                                filterValue([filters, setFilters], 'StartDate', Util.toDateString(newDate) + ' 00:00:00.000', 'ge');}} />                    
                    <DateTimePicker style={{ marginBottom:10 }} placeholder="종료일" useClear={true} onChange={(newDate) => {
                                filterValue([filters, setFilters], 'EndDate', Util.toDateString(newDate) + ' 23:59:59.998', 'le');}} />                                                    

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

                    <SearchTitle title="업체유형" />
                    <EntitySelect style={{ marginBottom:5 }} entity="CmPartnerType"  defaultLabel="업체유형" emptyLabel="전체" useCheck={true}
                        onChange={(item) => { 
                            filterValue([filters, setFilters], 'PartnerTypeId', item.value, 'eq');
                        }} />

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

                    <SearchTitle title="계약금액" />
                    <Input style={{ marginBottom:20 }} placeholder="계약금액" small onChangeText={value => filterValue([filters, setFilters], 'ContractAmountText', value, 'cn')} />
                </Fragment>
            </Search>
        </BottomTabBarLayout> 
        : null
    );
};

// header
Screen.navigationOptions = ({navigation}) => { 
    return { 
        header: () => <Header 
            navigation={navigation} 
            title="계약관리" 
            buttons={<SearchIcon id="contract" />}
        /> 
    } 
};

export default Screen;