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 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 { 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 [filters, setFilters] = useState({
        EmploymentStatus_ne:{field:'EmploymentStatus',op:'ne',value:3}
    });
    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();
    const { showCallOrMessageSelector } = usePhone();

    // 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 [companyTypeId, setCompanyTypeId] = useState('');
    return (
        <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} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            </SearchListContainer>

            <Search id="user" api={`api/app/users?siteId=${userinfo.SiteId}`} 
                    page={page} setPage={setPage} limit={50} filters={filters} sort={{field:'CmPosition.Position', order:'desc'}}
                    onStart={start} onSuccess={success} onFailure={fail} >
                <Fragment>
                    <SearchTitle title="회사구분" />
                    <EntitySelect style={{ marginBottom:20 }} entity="CmCompanyType" defaultLabel="회사구분" emptyLabel="전체" 
                        onChange={(item) => { 
                            setCompanyTypeId(item.value);
                            filterValue([filters, setFilters], 'CmCompany.CompanyTypeId', item.value, 'eq');
                        }} useCheck={true} />

                    <SearchTitle title="회사" />
                    <EntitySelect style={{ marginBottom:20 }} entity="CmCompany" siteId={userinfo.SiteId} defaultLabel="회사" emptyLabel="전체" 
                        where={`CompanyTypeId = '${companyTypeId}'`}
                        onChange={(item) => { filterValue([filters, setFilters], 'CompanyId', item.value, 'eq')}} useCheck={true} />

                    <SearchTitle title="사용자명" />
                    <Input style={{ marginBottom:20 }} placeholder="사용자명" small onChangeText={value => filterValue([filters, setFilters], 'Name', value, 'cn')} />
                </Fragment>
            </Search>
        </BottomTabBarLayout> 
    );
};

// header
Screen.navigationOptions = ({navigation}) => { 
    return { 
        header: () => <Header 
            navigation={navigation} 
            title="인원현황" 
            buttons={<SearchIcon id="user" />}
        /> 
    } 
};

export default Screen;