import React, { Fragment, useState, useEffect, useCallback, createRef, useRef } from 'react';
import { View, Text, Alert, FlatList, StyleSheet, TouchableOpacity, Image } 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 { Selectbox } from '~/Components/UIControls/Selectbox';
import Loading from '~/Components/UIControls/Loading';
import { fetchPost } from '~/Utils/fetch';
import MailIcon from '~/Assets/Svgs/list_mail.svg';
import PhoneIcon from '~/Assets/Svgs/list_phone.svg';
import { Util } from '~/Utils/utils';
import { useAuth } from '~/Components/Hooks';
import { TouchableWithoutFeedback } from 'react-native-gesture-handler';
import { usePhone } from '~/Components/UIControls/Phone';
import Icon from '~/Components/UIControls/Icon';

// list item
const Item = ({item, index, onPress=()=>{}, showCallOrMessageSelector=()=>{}}) => {
    const zebra = index % 2 == 0 ? true : false;
    const enterDate = Util.toDateString(Util.get(item, "EnterDate"));
    const mobilePhoneNo = Util.get(item, "MobilePhoneNo");
    const [imageLoading, setImageLoading] = useState(false);
    let phoneNumber = '';
    let mobileNumber = '';
    if(Util.get(item, "MobilePhoneNo") && Util.get(item, "OfficePhoneNo")) {
        phoneNumber = Util.get(item, "MobilePhoneNo") + " | " + Util.get(item, "OfficePhoneNo");
        mobileNumber = Util.get(item, "MobilePhoneNo");
    } else if(Util.get(item, "MobilePhoneNo")) {
        phoneNumber = Util.get(item, "MobilePhoneNo");
        mobileNumber = Util.get(item, "MobilePhoneNo");
    } else if(Util.get(item, "OfficePhoneNo")) {
        phoneNumber = Util.get(item, "OfficePhoneNo");
    }

    return (
        <TouchableOpacity onPress={onPress} style={{
            ...ListStyle.itemContainer, 
            borderTopWidth: 0, 
            backgroundColor: (zebra?'#fdfdfd':'#fff'),
        }}>
            <View style={{width:80}}>
                {!Util.get(item, "CmFile.Url") ? (
                    <View style={{width:70, height:90, backgroundColor:'#f5f5f5', alignItems:'center', justifyContent:'center'}}>
                        <Icon iconFamily="AntDesign" iconName="user" size={40} color="#9aa3ac" />
                    </View>
                ) : (
                    <Fragment>
                        <Image 
                            style={{width:70, height:90}} 
                            resizeMode='cover' 
                            source={{
                                uri:Util.get(item, "CmFile.Url"),
                                cache:'reload',
                                headers:{Pragma:'no-cache'}
                            }} 
                            onLoadStart={() => {
                                setImageLoading(true);
                            }} onLoadEnd={() => {
                                setImageLoading(false);
                            }} onError={() => {
                                setImageLoading(false);
                            }}
                        />
                        {imageLoading && (
                            <Loading style={{backgroundColor:'transparent'}} color="black" />
                        )}
                    </Fragment>
                )}
            </View>
            <View style={{...ListStyle.vertical, flex:1, marginRight:15}}>
                <View style={{...ListStyle.horizon, width:'100%', justifyContent:'space-between'}}>
                    <Text style={{...ListStyle.textMedium}}>
                        {Util.get(item, "CmCompany.Name")} 
                        {!!Util.get(item, "CmDepartment.Name") && <>({Util.get(item, "CmDepartment.Name")})</>}
                    </Text>
                </View>
                <Text style={{...ListStyle.textLightGray}}>
                    {Util.get(item, "CmPosition.Name")}&nbsp;{Util.get(item, "Name")}
                </Text>
                <Text style={{...ListStyle.textLightGray}}>
                    {enterDate && <Fragment>입사일&nbsp;:&nbsp;{enterDate}</Fragment>}
                </Text>
                <TouchableOpacity
                    onPress={() => {
                        if(!!mobilePhoneNo) {
                            showCallOrMessageSelector(mobilePhoneNo);
                        }
                    }}>
                    <Text style={{...ListStyle.textLightGray, ...ListStyle.horizon, alignItems:'center'}}>
                        <PhoneIcon width={16} height={13} />
                        <Text>&nbsp;&nbsp;{phoneNumber}</Text>
                    </Text>
                </TouchableOpacity>
            </View>
        </TouchableOpacity>
    )
}


// list and search
const Screen = (props) => {
    const navigation = props.navigation;
    const [ready, setReady] = useState(false);
    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 { auth } = useAuth(navigation);
    const [companyId, setCompanyId] = useState('');
    const { showMessage } = useToast();
    const isUseItems = useRef([
        {label:'사용', value:true}, 
        {label:'미사용', value:false}
    ]);

    const { showCallOrMessageSelector } = usePhone();

    //고용형태
    const employmentType = useRef([ 
        {label:'정규직', value:'1'}, 
        {label:'비정규직', value:'2'}
    ]);
    //근무상태
    const employmentStatus = useRef([ 
        {label:'재직', value:'1'}, 
        {label:'휴직', value:'2'},
        {label:'퇴직', value:'3'}
    ]);

    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} showCallOrMessageSelector={showCallOrMessageSelector} onPress={() => {
                                navigation.navigate('Form', {
                                    refreshList: refreshList,
                                    action: Form.VIEW, 
                                    siteId: session.getSiteId(), 
                                    userId: item.UserId, 
                                    auth : auth,
                                });
                            }} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
                <CreateButton onPress={() => {
                    navigation.navigate('Form', {
                        refreshList: refreshList,
                        action: Form.CREATE, 
                        siteId: session.getSiteId(), 
                        userId : 0, 
                        auth : auth
                    });
                }} />
            </SearchListContainer>

            <Search id="user" api={`api/app/users?siteId=${session.getSiteId()}`} 
                    page={page} setPage={setPage} limit={50} filters={filters} sort={{field:'CmPosition.Position', order:'desc'}}
                    onStart={start} onSuccess={success} onFailure={fail} >
                <Fragment>
                    <SearchTitle title="고용형태" />
                    <Selectbox style={{ marginBottom:20 }}  initialValue={true} defaultLabel="고용형태" emptyLabel="전체"
                        items={employmentType.current} 
                        onChange={item => {
                            filterValue([filters, setFilters], 'EmploymentType', item.value, 'eq');
                        }} />

                    <SearchTitle title="근무상태" />
                    <Selectbox style={{ marginBottom:20 }} initialValue={true} defaultLabel="근무상태" emptyLabel="전체"
                        items={employmentStatus.current} 
                        onChange={item => {
                            filterValue([filters, setFilters], 'EmploymentStatus', item.value, 'eq');
                        }} />                        


                    <SearchTitle title="회사/부서" />
                    <EntitySelect   style={{ marginBottom:5 }} entity="CmCompany"  siteId={session.getSiteId()}  defaultLabel="회사명" emptyLabel="전체" useCheck={true}
                                    onChange={(item) => { 
                                        filterValue([filters, setFilters], 'CompanyId', item.value, 'eq'); 
                                        setCompanyId(item.value);
                                    }} />
                    <EntitySelect   style={{ marginBottom:20 }} entity="CmDepartment"  siteId={session.getSiteId()}  defaultLabel="부서명" emptyLabel="전체" useCheck={true}
                                    where={companyId != '' ? `CompanyId=${companyId}`:``}
                                    onChange={(item) => { 
                                        filterValue([filters, setFilters], 'DepartmentId', item.value, 'eq'); 
                                    }} />

                    <SearchTitle title="이름" />
                    <Input style={{ marginBottom:20 }} placeholder="이름" small onChangeText={value => filterValue([filters, setFilters], 'Name', value, 'cn')} />
                        
                    <SearchTitle title="사용여부" />
                    <Selectbox style={{ marginBottom:20 }} initialValue={true} defaultLabel="사용여부" emptyLabel="전체"
                        items={isUseItems.current}
                        onChange={item => {
                            filterValue([filters, setFilters], 'IsUse', item.value, 'eq');
                        }} />

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

// header
Screen.navigationOptions = ({navigation}) => { 
    return { 
        header: () => <Header 
            navigation={navigation} 
            title="사용자관리" 
            buttons={<SearchIcon id="user" />}
        /> 
    } 
};

export default Screen;