import React, { Fragment, useEffect, useRef, useState } from 'react';
import Styled from 'styled-components/native';
import { View, Text, TouchableOpacity } from   'react-native';
import IconButton from '~/Components/UIControls/IconButton';
import { PopupLayout, useLayoutAction } from '~/Components/Layouts/PopupLayout';
import Button from '~/Components/UIControls/Button';
import { SearchBoxIcon, PrimaryButton, Search, filterValue, checkFilter, DetailIcon, ListStyle, DefaultButton, SearchTitle } from '~/Components/Listing/Search';
import session from '~/Utils/session';
import Checkbox from '~/Components/UIControls/Checkbox';
import EntitySelect from '~/Components/EntitySelect';
import Input from '~/Components/UIControls/Input';
import { Util } from '~/Utils/utils';
import MailIcon from '~/Assets/Svgs/list_mail.svg';
import PhoneIcon from '~/Assets/Svgs/list_phone.svg';
import SearchList from '~/Components/Listing/SearchList';
import { DefaultAction } from '~/Components/UIControls/Popup/Context';
import { useToast } from '~/Components/UIControls/Message';


const Item = ({item, index, onPress=()=>{}}) => {
    const zebra = index % 2 == 0 ? true : false;
    const enterDate = Util.toDateString(item.EnterDate);
    return (
        <TouchableOpacity onPress={onPress} style={{
            ...ListStyle.itemContainer, 
            borderTopWidth: (index==0?1:0), 
            backgroundColor: (zebra?'#fdfdfd':'#fff'),
        }}>
            <View style={{...ListStyle.vertical, flex:1, marginRight:15}}>
                <View style={{...ListStyle.horizon, width:'100%', justifyContent:'space-between'}}>
                    <Text style={{...ListStyle.textMedium}}>
                        {item.CmCompany.CmCompanyType.Name}&nbsp;{item.CmCompany.Name}
                    </Text>
                    <Text style={{...ListStyle.textLightGray}}>
                        {enterDate && <Fragment>입사일&nbsp;:&nbsp;{enterDate}</Fragment>}
                    </Text>
                </View>
                <Text style={{...ListStyle.textLight}}>
                        {item.Name}&nbsp;{item.CmPosition.Name}&nbsp;({item.CmBusinessField.Name})
                    </Text>
                <Text style={{...ListStyle.textLightGray, ...ListStyle.horizon, alignItems:'center'}}>
                    <MailIcon width={16} height={13} />&nbsp;&nbsp;{item.Email}
                </Text>
                <Text style={{...ListStyle.textLightGray, ...ListStyle.horizon, alignItems:'center'}}>
                    <PhoneIcon width={16} height={13} />&nbsp;&nbsp;
                    {(() => {
                        if(item.MobilePhoneNo && item.OfficePhoneNo) {
                            return item.MobilePhoneNo + " | " + item.OfficePhoneNo;
                        } else if(item.MobilePhoneNo) {
                            return item.MobilePhoneNo;
                        } else if(item.OfficePhoneNo) {
                            return item.OfficePhoneNo;
                        } else {
                            return "";
                        }
                    })()}
                </Text>
            </View>
        </TouchableOpacity>
    )
}

const Container = Styled.View`
    flex: 1;
    background-color: #fff;
    padding-top: 17px;
    padding-bottom: 17px;
`;

export default Popup = ({siteId=0, popup=DefaultAction}) => {
    const [filters, setFilters] = useState({});
    const [list, setList] = useState(null);
    const [page, setPage] = useState(1);
    const [refreshing, setRefreshing] = useState(false);
    const pages = useRef(10);
    const { showMessage } = useToast();

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

    // search events...
    const start = () => {
        console.log("user popup search start");
        setRefreshing(true);
    }
    const success = (data, append) => {
        console.log("user popup search success");
        pages.current = data.pages;
        console.log('total pages : ', data.pages);
        //console.log(data);

        if(append && page > 1) {
            setList(list.concat(data.list));
        } else {
            setList(data.list);
        }
        setRefreshing(false);
    }
    const fail = (e) => {
        console.log("user popup search fail");
        showMessage(e.message);
        setRefreshing(false);
    }

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

    const [companyTypeId, setCompanyTypeId] = useState('');
    return (
        <PopupLayout title="사용자 선택" header={Header} actionHandler={actionHandler}>
            <Container>
                <SearchList page={page} pages={pages.current} setPage={setPage} refreshing={refreshing}
                    data={list} keyExtractor={item => item.SiteId+'_'+item.UserId} renderItem={({ item, index }) => {
                        return (
                            <Item item={item} index={index} onPress={() => {
                                popup.select({UserId: item.UserId, Name: item.Name});
                            }} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            </Container>

            <Search id="user-popup" api={`api/app/users?siteId=${siteId}`} 
                    page={page} setPage={setPage} limit={20} filters={filters} sort={{field:'UserId', order:'asc'}}
                    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={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>
        </PopupLayout>
    );
};

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

    return (
        <Fragment>
            <DefaultButton style={{marginRight:5}} onPress={() => { callAction('onClose') }}>닫기</DefaultButton>
            <SearchBoxIcon id="user-popup" />
        </Fragment>
    )
}