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';

const style = StyleSheet.create({
    container : {flexDirection:'column'},
    header : {padding: 15, paddingLeft:0, paddingBottom:5, flexDirection:'row', alignItems:"center", justifyContent:"center"},
    headerBadge : {width:63,height:28,borderRadius:14,marginRight:5,borderStyle:'solid',borderWidth:1,borderColor:'#0b83e6',alignItems:'center',justifyContent:'center'},
    headerBadgeText : {color:'#0b83e6',fontSize:14,textAlign:'center',fontFamily:Theme.Fonts.RobotoRegular},
    headerName : {fontSize:16, lineHeight:28, color:'#000'},
    headerDetail : {marginLeft:15, flexDirection:'column', flex:1},
    headerUnit : {color:'#b9bac4', fontSize:14},
    info : {padding:15, paddingVertical:5},
    infoContainer : {flexDirection:'row'},
    infoLabel : {color:'#b9bac4', fontSize:16, marginRight:'auto'},
    infoValue : {color:'#b9bac4', fontSize:16, marginLeft:'auto'},
    headerState : {height:30,alignItems:'center',justifyContent:'center'},
    headerStateText : {color:'#000', fontFamily:Theme.Fonts.Regular, fontSize:16},
    stock : {paddingHorizontal:15, paddingVertical:8, backgroundColor:'#f8fcff', flexDirection:'row'},
    stockLabel : {color:'#9aa3ac',fontSize:16, fontFamily: Theme.Fonts.Regular},
    stockValue : {fontWeight:"500",fontSize:16, fontFamily: Theme.Fonts.Regular},
    detail : {padding: 15, flexDirection: 'row', justifyContent :'space-between'},
    detailBadge : {width:70,height:70,borderRadius:70,borderStyle:'solid',borderWidth:1,borderColor:'#9aa3ac',alignItems:'center',justifyContent:'center'},
    detailBadgeText : {color:'#000',fontSize:22,textAlign:'center',fontFamily:Theme.Fonts.RobotoRegular},
    detailBadgeLabel : {textAlign:'center', marginTop:5},
    detailLabel : {fontFamily: Theme.Fonts.RobotoRegular },
});

// list item
class Item extends React.PureComponent {
    render() {
        const {item, index, config, onPress} = this.props;
        const zebra = index % 2 == 0 ? true : false;
        return (
            <TouchableOpacity onPress={onPress} style={{
                marginBottom:10,
                borderTopWidth:1,
                borderTopColor:'#e9e9e9',
                backgroundColor: (zebra?'#fdfdfd':'#fff'),
            }}>
                <View style={style.container}>
                    <View style={style.header}>
                        <View style={style.headerDetail}>
                            <View style={style.infoContainer}>
                                <View style={style.headerBadge}><Text style={style.headerBadgeText}>{item.EquipmentTypeName}</Text></View>
                                <Text style={style.headerName}>{item.Name}</Text>
                            </View>
                            <Text style={style.headerUnit}>{[item.Standard,item.Unit].filter(e=>e).join('/')}</Text>
                        </View>
                        <View>
                            <View style={style.headerState}><Text style={style.headerStateText}>{item.WarehouseName}</Text></View>
                        </View>
                    </View>
                    <View style={style.info}>
                        <View style={style.infoContainer}>
                            <Text style={style.infoLabel}>등록일자</Text>
                            <Text style={style.infoValue}>{Util.getDateString(item, 'AddDate', '.')}</Text>
                        </View>
                        <View style={style.infoContainer}>
                            <Text style={style.infoLabel}>손실사유</Text>
                            <Text style={style.infoValue}>{Util.get(item, 'ReturnReason')}</Text>
                        </View>
                        <View style={style.infoContainer}>
                            <Text style={style.infoLabel}>승인자</Text>
                            <Text style={style.infoValue}>{Util.get(item, 'ReturnApprovalUserName')}</Text>
                        </View>
                        <View style={style.infoContainer}>
                            <Text style={style.infoLabel}>승인일자</Text>
                            <Text style={style.infoValue}>{Util.getDateString(item, 'ReturnApprovalDate', '.')}</Text>
                        </View>
                        {config.UseEquipmentRent && (
                            <View style={style.infoContainer}>
                                <Text style={style.infoLabel}>대여자</Text>
                                <Text style={style.infoValue}>{Util.get(item, 'RentUserName')}</Text>
                            </View>
                        )}
                    </View>
                    {config.UseEquipmentRent && (
                        <View style={[style.stock]}>
                            <Text style={{...style.stockLabel, marginRight:9}}>반납수량</Text>
                            <Text style={{...style.stockValue}}>{Util.toPrice(item.ReturnCount)}</Text>
                        </View>
                    )}
                    <View style={[style.stock]}>
                        <Text style={{...style.stockLabel, marginRight:9}}>손실수량</Text>
                        <Text style={{...style.stockValue}}>{Util.toPrice(item.LossCount)}</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, config } = useAuth(navigation);
    const { showMessage } = useToast();

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

    // 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} config={config} onPress={() => {
                                navigation.navigate('Form', {
                                    refreshList: refreshList,
                                    action: Form.VIEW, 
                                    siteId: session.getSiteId(), 
                                    equipmentId: item.EquipmentId, 
                                    historyId: item.EquipmentHistoryId,
                                    auth: auth,
                                    userinfo: userinfo,
                                    config: config,
                                });
                            }} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
                {auth.Update && (
                    <CreateButton onPress={() => {
                        navigation.navigate('Form', {
                            refreshList: refreshList,
                            action: Form.CREATE, 
                            siteId: session.getSiteId(), 
                            equipmentId: 0, 
                            historyId: 0,
                            auth: auth,
                            userinfo: userinfo,
                            config: config,
                        });
                    }} />
                )}
            </SearchListContainer>

            <Search id="equipment-search" api={`api/app/EquipmentHistory/ReturnList?siteId=${session.getSiteId()}`} 
                    page={page} setPage={setPage} limit={50} filters={filters} sort={{field:'EquipmentId', order:'desc'}}
                    onStart={start} onSuccess={success} onFailure={fail} >
                <Fragment>
                    <SearchTitle title="분류" />
                    <EntitySelect 
                        style={{ marginBottom:20 }} 
                        entity="FmsEquipmentCodeType" id="EquipmentTypeId" useCheck={true}
                        defaultLabel="분류" emptyLabel="전체"
                        onChange={(item) => { 
                            filterValue([filters, setFilters], 'FmsEquipment.EquipmentTypeId', item.value, 'eq');
                        }} />

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

                    <SearchTitle title="규격" />
                    <Input style={{ marginBottom:20 }} placeholder="규격" small onChangeText={value => filterValue([filters, setFilters], 'FmsEquipment.Standard', value, 'cn')} />

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

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

// header
Screen.navigationOptions = ({navigation}) => { 
    return { 
        header: () => <Header 
            navigation={navigation} 
            title="공기구현황" 
            buttons={<SearchIcon id="equipment-search" />}
        /> 
    } 
};

export default Screen;