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 { WorkInfo } from '../Common/WorkInfo';
import { useAuth } from '~/Components/Hooks';

// 작업진행 관리 (base WorkResult, ProgressType:(4,7))
// 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.fillRounded,
                        backgroundColor:Theme.WorkProgressColor[Util.get(item, "WorkProgress.Name")]
                    }}>{Theme.WorkProgressName[Util.get(item, "WorkProgress.Name")]}</Text>
                    <Text>&nbsp;&nbsp;</Text>
                    <Text style={{...ListStyle.fillRounded, backgroundColor:Theme.WorkTypeColor[Util.get(item, "WorkType.Name", "")]}}>
                        {Theme.WorkTypeName[Util.get(item, "WorkType.Name")]}
                    </Text>
                    <Text>&nbsp;&nbsp;</Text>
                    <Text style={{...ListStyle.rounded}}>{Util.get(item, "BusinessField.Name")}</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 style={{...ListStyle.horizon, width:'100%', paddingRight:15, justifyContent:'space-between'}}>
                    <Text style={{...ListStyle.textLightGray}}>업체명</Text>
                    <Text style={{...ListStyle.textLightGray}}>{Util.get(item, "WorkPartnerName")}</Text>
                </View>
                <View style={{...ListStyle.horizon, width:'100%', paddingRight:15, justifyContent:'space-between'}}>
                    <Text style={{...ListStyle.textLightGray}}>작업자</Text>
                    <Text style={{...ListStyle.textLightGray}}>{Util.get(item, "WorkerUser.Name")}</Text>
                </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, userinfo } = useAuth(navigation);
    const pages = useRef(10);
    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>
            <WorkInfo />
            <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, 
                                    workRequestId: item.WorkRequestId, 
                                    workProgressId: item.WorkProgressId,
                                    workTypeId: item.WorkTypeId,
                                    hasCheckItem: item.HasCheckItem,
                                    auth: auth,
                                    userinfo: userinfo,
                                });
                            }} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            </SearchListContainer>

            <Search id="work-process" api={`api/app/WorkResult?siteId=${userinfo.SiteId}&workProgressId=4&businessAuth=${auth.Business}`} 
                    page={page} setPage={setPage} setPage={setPage} limit={50} filters={filters} sort={{field:'FmsWorkOrder.OrderDate', 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], 'BusinessFieldId', item.value, 'eq');
                        }} />

                    <SearchTitle title="작업구분" />
                    <EntitySelect style={{ marginBottom:20 }} entity="FmsWorkCodeType" 
                        defaultLabel="작업구분" emptyLabel="전체" id="WorkTypeId" name="Name" excludes={[3,4]}
                        onChange={(item) => { 
                            filterValue([filters, setFilters], 'FmsWorkRequest.WorkTypeId', 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], 'StartDate', Util.toDateString(newDate), 'le');
                    }} />

                    <SearchTitle title="작업종료일" />
                    <DateTimePicker style={{ marginBottom:5 }} placeholder="부터" useClear={true} onChange={(newDate) => {
                        filterValue([filters, setFilters], 'EndDate', Util.toDateString(newDate), 'ge');
                    }} />
                    <DateTimePicker style={{ marginBottom:20 }} placeholder="까지" useClear={true} onChange={(newDate) => {
                        filterValue([filters, setFilters], 'EndDate', Util.toDateString(newDate), 'le');
                    }} />

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

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

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

// header
Screen.navigationOptions = ({navigation}) => { 
    return { 
        header: () => <Header 
            navigation={navigation} 
            title="작업진행 관리" 
            buttons={<SearchIcon id="work-process" />}
        /> 
    } 
};

export default Screen;