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=()=>{}}) => {
    const zebra = index % 2 == 0 ? true : false;
    return (
        <TouchableOpacity onPress={onPress} style={[ListStyle.itemContainer, {backgroundColor: (zebra?'#fdfdfd':'#fff')}]}>
            <View style={[ListStyle.vertical, { flex:1, marginRight:15 }]}>
                <Text style={[ListStyle.text]}>{Util.get(item, "FormatName")}</Text>
                <Text style={[ListStyle.text]}>{Util.get(item, "ReportName")}</Text>
                <View style={[ListStyle.horizon, {flex:1, marginTop:10}]}>
                    <Text style={[ListStyle.textGray, {flex:1}]}>{Util.get(item, "Writer")}</Text>
                    <Text style={[ListStyle.textGray]}>{Util.getDateString(item, "CreateDate")}</Text>
                </View>
                <View style={[ListStyle.horizon, {flex:1}]}>
                    <Text style={[ListStyle.textGray, {flex:1}]}>팀장확인</Text>
                    <Text style={[ListStyle.textGray]}>{Util.get(item, "Confirm1")}</Text>
                </View>
                <View style={[ListStyle.horizon, {flex:1}]}>
                    <Text style={[ListStyle.textGray, {flex:1}]}>소장확인</Text>
                    <Text style={[ListStyle.textGray]}>{Util.get(item, "Confirm2")}</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();

    // 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);
    }

    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, 
                                    seq: item.Seq, 
                                    datetime: item.CreateDate,
                                    reportFormatId: item.ReportFormatId,
                                    auth: auth,
                                    userinfo: userinfo,
                                });
                            }} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            </SearchListContainer>

            <Search id="report-history-search" api={`api/app/ReportHistory?siteId=${userinfo.SiteId}&businessAuth=${auth.Business}`} 
                    page={page} setPage={setPage} limit={50} filters={filters} sort={{field:'FacilityCode', order:'desc'}}
                    onStart={start} onSuccess={success} onFailure={fail} >
                <Fragment>
                    <SearchTitle title="업무분야" />
                    <EntitySelect style={{ marginBottom:20 }} entity="CmBusinessField"
                        defaultLabel="업무분야" emptyLabel="전체" useCheck={true} auth={auth}
                        onChange={(item) => { 
                            filterValue([filters, setFilters], 'BemsReportFormat.BusinessFieldId', item.value, 'eq');
                        }} auth={auth} />

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

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

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

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

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

// header
Screen.navigationOptions = ({navigation}) => { 
    return { 
        header: () => <Header 
            navigation={navigation} 
            title="일지관리" 
            buttons={<SearchIcon id="report-history-search" />}
        /> 
    } 
};

export default Screen;