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 Header from '~/Components/Layouts/Header';
import {
    Search,
    SearchIcon,
    Line,
    TextInput,
    checkFilter,
    filterValue,
    ListStyle,
    DetailIcon,
    RightArrow,
    CreateButton,
    SearchTitle,
    DetailButton,
} 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 PhoneIcon from '~/Assets/Svgs/list_phone.svg';
import { Util } from '~/Utils/utils';
import { useAuth } from '~/Components/Hooks';
import { Selectbox } from '~/Components/UIControls/Selectbox';
import { usePhone } from '~/Components/UIControls/Phone';
// list item
const Item = ({ item, index, onPress = () => {}, showCallOrMessageSelector = () => {} }) => {
    //console.log(item);
    const zebra = index % 2 == 0 ? true : false;

    return (
        <View
            style={{
                ...ListStyle.itemContainer,
                borderTopWidth: 0,
                backgroundColor: zebra ? '#fdfdfd' : '#fff',
            }}
        >
            <View style={{ ...ListStyle.horizon, flex: 1 }}>
                <View style={{ ...ListStyle.vertical, paddingLeft: 10, flex: 1 }}>
                    <View style={{ ...ListStyle.vertical }}>
                        <View style={{ ...ListStyle.horizon }}>
                            <Text style={{ ...ListStyle.rounded }}>{Util.get(item, 'PartnerTypeName')}</Text>
                            <Text style={{ ...ListStyle.textMedium, marginLeft: 10 }}>{Util.get(item, 'Name')}&nbsp;&nbsp;</Text>
                        </View>
                        <TouchableOpacity
                            onPress={() => {
                                showCallOrMessageSelector(Util.get(item, 'PhoneNo'));
                            }}
                        >
                            <Text style={{ ...ListStyle.textLight }}>
                                {Util.get(item, 'RepresentativeName') && (
                                    <Fragment>담당 : {Util.get(item, 'RepresentativeName')}&nbsp;&nbsp;&nbsp;&nbsp;</Fragment>
                                )}
                                <PhoneIcon width={16} height={13} />
                                &nbsp;&nbsp;{Util.get(item, 'PhoneNo')}
                            </Text>
                        </TouchableOpacity>
                    </View>
                </View>
                <DetailButton onPress={onPress} />
            </View>
        </View>
    );
};

// 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 { auth, userinfo, config } = useAuth(navigation);
    const pages = useRef(10);
    const { showMessage } = useToast();
    const isUseItems = useRef([
        { label: '사용', value: true },
        { label: '미사용', value: false },
    ]);
    const { showCallOrMessageSelector } = usePhone();

    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}
                    config={config}
                    pages={pages.current}
                    setPage={setPage}
                    refreshing={refreshing}
                    data={list}
                    renderItem={({ item, index }) => {
                        return (
                            <Item
                                item={item}
                                index={index}
                                onPress={() => {
                                    navigation.navigate('Form', {
                                        refreshList: refreshList,
                                        action: Form.VIEW,
                                        siteId: session.getSiteId(),
                                        partnerId: item.PartnerId,
                                        auth: auth,
                                        config: config,
                                    });
                                }}
                                showCallOrMessageSelector={showCallOrMessageSelector}
                            />
                        );
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
                {auth.Update && (
                    <CreateButton
                        onPress={() => {
                            navigation.navigate('Form', {
                                refreshList: refreshList,
                                action: Form.CREATE,
                                siteId: session.getSiteId(),
                                partnerId: 0,
                                auth: auth,
                                config: config,
                            });
                        }}
                    />
                )}
            </SearchListContainer>

            <Search
                id="partner"
                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="업체명" />
                    <Input
                        style={{ marginBottom: 20 }}
                        placeholder="업체명"
                        small
                        onChangeText={(value) => filterValue([filters, setFilters], 'Name', value, 'cn')}
                    />

                    <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], 'SalesName', value, 'cn')}
                    />
                    
                    <SearchTitle title="전화번호" />
                    <Input
                        style={{ marginBottom: 20 }}
                        placeholder="전화번호"
                        small
                        onChangeText={(value) => filterValue([filters, setFilters], 'PhoneNo', value, 'cn')}
                    />
                    
                    <SearchTitle title="사업자번호" />
                    <Input
                        style={{ marginBottom: 20 }}
                        placeholder="사업자번호"
                        small
                        onChangeText={(value) => filterValue([filters, setFilters], 'RegistrationNo', 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="partner" />} />,
    };
};

export default Screen;
