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

// list item
const Item = ({item, index, onPress=()=>{}}) => {
    //console.log(item);
    const zebra = index % 2 == 0 ? true : false;
    
    return (
        <TouchableOpacity onPress={onPress} style={{
            ...ListStyle.itemContainer, 
            borderTopWidth: 0, 
            backgroundColor: (zebra?'#fdfdfd':'#fff')
        }}>
            <View style={{...ListStyle.horizon, flex:1}}>
                <View style={{...ListStyle.typeRounded,alignItems:"center",justifyContent:"center"}}>
                    <Text style={{ ...ListStyle.textLightGrayLargeTypeRounded}}>
                        {Util.get(item, "PartnerTypeName")}
                    </Text>
                </View>
                <View style={{...ListStyle.vertical,paddingLeft:15, flex:1}}>
                    <View style={{...ListStyle.vertical}}>
                        <View style={{...ListStyle.horizon}}>
                            <Text style={{...ListStyle.textMedium}}>{Util.get(item, "Name")}&nbsp;&nbsp;</Text>
                            {Util.get(item,"RepresentativeName")  && <Text style={{...ListStyle.textMedium}}> {Util.get(item, "RepresentativeName")} </Text>}
                        </View>
                        <Text style={{...ListStyle.textLight}}>
                            <PhoneIcon width={16} height={13} />&nbsp;&nbsp;{Util.get(item, "PhoneNo")}
                        </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 } = 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} onPress={() => {
                                popup.select(item);
                            }} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            </Container>

            <Search id="partner-popup" api={`api/app/Partner?siteId=${session.getSiteId()}&useServicePartner=${config.UseServicePartner}&businessAuth=${auth.Business}`} 
                    page={page} setPage={setPage} limit={50} filters={filters} sort={{field:'PartnerId', order:'desc'}}
                    onStart={start} onSuccess={success} onFailure={fail} >
                <Fragment>
                    <SearchTitle title="업무분야" />
                    <EntitySelect style={{ marginBottom:20 }} entity="CmBusinessField"
                        defaultLabel="업무분야" emptyLabel="전체" useCheck={true} auth={auth}
                        onChange={(item) => { 
                            filterValue([filters, setFilters], 'BusinessFieldId', item.value, 'eq');
                        }} auth={auth} />

                    <SearchTitle title="업체유형" />
                    <EntitySelect style={{ marginBottom:20 }} entity="CmPartnerType"  defaultLabel="업체유형" emptyLabel="전체" useCheck={true}  where={config.UseServicePartner ? `Name != '용역업체'` :`1 = 1` } 
                        onChange={(item) => { 
                            filterValue([filters, setFilters], 'PartnerTypeId', 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>

        </PopupLayout> 
    );
};

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

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