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 { Search, SearchIcon, Line, TextInput, checkFilter, filterValue, ListStyle, DetailIcon, RightArrow, CreateButton, SearchBoxIcon, DefaultButton, PrimaryButton, 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 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 { useLayoutAction, PopupLayout } from '~/Components/Layouts/PopupLayout';
import Icon from '~/Components/UIControls/Icon';
import { Util } from '~/Utils/utils';
import { Selectbox } from '~/Components/UIControls/Selectbox';
import { useAuth } from '~/Components/Hooks';
import PhoneIcon from '~/Assets/Svgs/list_phone.svg';


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,borderStyle:'solid',borderWidth:1,borderColor:'#0b83e6',alignItems:'center',justifyContent:'center'},
    headerBadgeText : {color:'#0b83e6',fontSize:14,textAlign:'center',fontFamily:Theme.Fonts.RobotoRegular},
    headerName : {fontSize:16, color:'#000'},
    headerDetail : {marginLeft:15, flexDirection:'column', flex:1},
    headerUnit : {color:'#b9bac4', fontSize:14},
    info : {padding:15, paddingVertical:10},
    infoContainer : {flexDirection:'row', alignItems:'center'},
    infoLabel : {color:'#b9bac4', fontSize:16, marginRight:'auto'},
    infoValue : {color:'#b9bac4', fontSize:16, marginLeft:'auto'},
    headerState : {backgroundColor:'#000', borderRadius:15, width:66, height:30,alignItems:'center',justifyContent:'center'},
    headerStateText : {color:'white', 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-around'},
    detailBadge : {width:60,height:60,borderRadius:60,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 },
});

const stateColor = (state) => {
    const colors = {
        '입고':'#0b83e6',
        '대여':'#ffb801',
        '반납':'#0eb118',
        '손실':'#f2335c',
    };
    return colors[state] ? colors[state] : '#000';
}

// list item
const Item = ({item, index, config, onPress=()=>{}}) => {
    //console.log(item);
    const zebra = index % 2 == 0 ? true : false;
    
    return (
        <TouchableOpacity style={{
            marginBottom:10,
            borderTopWidth:1,
            borderTopColor:'#e9e9e9',
            backgroundColor: (zebra?'#fdfdfd':'#fff'),
        }} onPress={onPress}>
            <View style={style.container}>
                <View style={style.header}>
                    <View style={style.headerDetail}>
                        <View style={style.headerBadge}><Text style={style.headerBadgeText}>{item.EquipmentTypeName}</Text></View>
                        <Text style={style.headerName}>{item.Name}</Text>
                        <Text style={style.headerUnit}>{[item.Standard,item.Unit].filter(e=>e).join('/')}</Text>
                    </View>
                </View>
                <View style={style.info}>
                    <View style={style.infoContainer}>
                        <Text style={style.infoLabel}>{config.UseEquipmentRent ? '대여수량' : '입고수량'}</Text>
                        <Text style={style.infoValue}>{Util.get(item, 'CurrentRentCount')}</Text>
                    </View>
                    {config.UseEquipmentRent ? (
                        <Fragment>
                            <View style={style.infoContainer}>
                                <Text style={style.infoLabel}>대여자</Text>
                                <Text style={style.infoValue}>{Util.get(item, 'RentUserName')}</Text>
                            </View>
                            <View style={style.infoContainer}>
                                <Text style={style.infoLabel}>대여일</Text>
                                <Text style={style.infoValue}>{Util.getDateString(item, 'RentDate', '.')}</Text>
                            </View>
                            <View style={style.infoContainer}>
                                <Text style={style.infoLabel}>반납예정일</Text>
                                <Text style={style.infoValue}>{Util.getDateString(item, 'ReturnDueDate', '.')}</Text>
                            </View>
                        </Fragment>
                    ) : (
                        <View style={style.infoContainer}>
                            <Text style={style.infoLabel}>등록일</Text>
                            <Text style={style.infoValue}>{Util.getDateString(item, 'AddDate', '.')}</Text>
                        </View>
                    )}
                </View>
            </View>
        </TouchableOpacity>
    )
}

// list and search
const Container = Styled.View`
    flex: 1;
    background-color: #fff;
    padding-top: 17px;
    padding-bottom: 17px;
`;
export default Popup = ({navigation, siteId=0, popup=DefaultAction}) => {
    const [filters, setFilters] = useState({IsUse_eq:{field:'IsUse',op:'eq',value:true}});
    const [list, setList] = useState(null);
    const [page, setPage] = useState(1);
    const [refreshing, setRefreshing] = useState(false);
    const pages = useRef(10);
    const checkedItems = useRef([]);
    const { showMessage } = useToast();
    const isUseItems = useRef([
        {label:'사용', value:true}, 
        {label:'미사용', value:false}
    ]);
    const { config, auth, userinfo } = useAuth(navigation);

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

    // header button handler
    const actionHandler = (action, parameter = {}) => {
        const actions = {
            close: () => {
                console.log('close...');
                popup.close();
            }
        }
        actions[action]();
    }

    return (
        <PopupLayout title="공기구선택" header={Header} actionHandler={actionHandler}>
            <Container>
                <SearchList page={page} config={config} pages={pages.current} setPage={setPage} refreshing={refreshing}
                    data={list} renderItem={({ item, index }) => {
                        return (
                            <Item item={item} index={index} config={config} onPress={() => {
                                popup.select(item);
                            }} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            </Container>

            <Search id="rent-list-popup" api={`api/app/EquipmentHistory/RentList?siteId=${session.getSiteId()}`} 
                    page={page} setPage={setPage} limit={50} filters={filters}
                    onStart={start} onSuccess={success} onFailure={fail} >
            </Search>

        </PopupLayout> 
    );
};

const Header = () => {
    const { callAction } = useLayoutAction();

    return (
        <Fragment>
            <DefaultButton onPress={() => { callAction('close') }}>닫기</DefaultButton>
        </Fragment>
    )
}
