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

// list item
const Item = ({item, index, onPress=()=>{}, convertToPyung=()=>{}}) => {
    const zebra = index % 2 == 0 ? true : false;

    return (
        <TouchableOpacity onPress={onPress} style={{
            ...ListStyle.itemContainer, 
            borderTopWidth: 0, 
            backgroundColor: (zebra?'#fdfdfd':'#fff')
        }}>
            <View style={{...ListStyle.vertical, flex:1}}>
                <View style={{...ListStyle.horizon}}>
                    <Text style={{...ListStyle.rounded}}>{Util.get(item, "CmFloor.Name")}</Text>
                    <Text style={{...ListStyle.textLight, marginLeft:10}}>{Util.get(item, "CmCompanyType.Name")}&nbsp;&nbsp;</Text>
                    <Text style={{...ListStyle.textMedium}}>{Util.get(item, "Name")}&nbsp;&nbsp;</Text>
                </View>
                <Text style={{...ListStyle.textLight}}>
                    <PhoneIcon width={16} height={13} />&nbsp;&nbsp;{Util.get(item, "RepresentativePhone")}
                </Text>
                <Text style={{...ListStyle.textLight}}>
                    <Text>임대면적&nbsp;&nbsp;</Text>
                    <Text>{Util.get(item, "AreaSize")}㎡ ({convertToPyung(Util.get(item, "AreaSize"))}평)</Text>
                </Text>
                <Text style={{...ListStyle.textLight}}>
                    <Text>전용면적&nbsp;&nbsp;</Text>
                    <Text>{Util.get(item, "ExclusiveArea")}㎡ ({convertToPyung(Util.get(item, "ExclusiveArea"))}평)</Text>
                </Text>
            </View>
            <DetailIcon />
        </TouchableOpacity>
    )
}

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

    const [searchForm, setSearchForm] = useState({
        BuildingId: '',
        FloorId: '',
    });

    const convertToPyung = (value) => {
        return (Util.parseFloat(value) / 3.30579).toFixed(2) + '';
    }

    console.log('filters : ', filters);

    // 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 refreshList = () => {
        setPage('refresh-' + Math.random());
    }

    return (
        <BottomTabBarLayout>
            <SearchListContainer>
                <SearchList page={page} pages={pages.current} setPage={setPage} refreshing={refreshing}
                    data={list} renderItem={({ item, index }) => {
                        return (
                            <Item item={item} index={index} convertToPyung={convertToPyung} onPress={() => {
                                navigation.navigate('Form', {
                                    refreshList: refreshList,
                                    action: Form.VIEW, 
                                    siteId: userinfo.SiteId, 
                                    tenantId: item.TenantId, 
                                    auth: auth,
                                    userinfo: userinfo,
                                });
                            }} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
                {auth.Update && (<CreateButton onPress={() => {
                    navigation.navigate('Form', {
                        refreshList: refreshList,
                        action: Form.CREATE, 
                        siteId: userinfo.SiteId, 
                        tenantId: 0, 
                        auth: auth,
                        userinfo: userinfo,
                    });
                }} />)}
            </SearchListContainer>

            <Search id="tenant" api={`api/app/Tenant?siteId=${userinfo.SiteId}`} 
                    page={page} setPage={setPage} limit={50} filters={filters} sort={{field:'CmFloor.FloorCode', order:'asc'}}
                    onStart={start} onSuccess={success} onFailure={fail} >
                <Fragment>

                    <SearchTitle title="빌딩명" />
                    <EntitySelect style={{ marginBottom:20 }} entity="CmBuilding" siteId={userinfo.SiteId} defaultLabel="빌딩" emptyLabel="전체" useCheck={true}
                        onChange={(item) => { 
                            setSearchForm({...searchForm,
                                BuildingId: item.value,
                                FloorId: '',
                            });
                            filterValue([filters, setFilters], 'BuildingId', item.value, 'eq');
                        }} />

                    <SearchTitle title="층명" />
                    <EntitySelect style={{ marginBottom:20 }} entity="CmFloor" siteId={userinfo.SiteId} defaultLabel="층" emptyLabel="전체" 
                        where={`BuildingId = '${searchForm.BuildingId}'`}
                        onChange={(item) => { 
                            setSearchForm({...searchForm,
                                FloorId: item.value,
                            });
                            filterValue([filters, setFilters], 'FloorId', item.value, 'eq');
                        }} />

                    <SearchTitle title="회사구분" />
                    <EntitySelect style={{ marginBottom:20 }} entity="CmCompanyType" defaultLabel="분류1" emptyLabel="전체" useCheck={true}
                        onChange={(item) => { 
                            filterValue([filters, setFilters], 'CompanyTypeId', 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> 
    );
};

// header
Screen.navigationOptions = ({navigation}) => { 
    return { 
        header: () => <Header 
            navigation={navigation} 
            title="입주사정보" 
            buttons={<SearchIcon id="tenant" />}
        /> 
    } 
};

export default Screen;