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

// list item
const Item = ({item, index, onChecked=()=>{}}) => {
    const zebra = index % 2 == 0 ? true : false;
    const [checked, setChecked] = useState(false);
    return (
        <TouchableOpacity onPress={() => {
            setChecked(!checked);
            onChecked(item, !checked);
        }} style={{
            ...ListStyle.itemContainer, 
            borderTopWidth: (index==0?1:0), 
            backgroundColor: (zebra?'#fdfdfd':'#fff'),
        }}>
            <View style={{...ListStyle.vertical}}>
                <View style={{...ListStyle.horizon}}>
                    <Text style={{...ListStyle.rounded}}>{Util.get(item, "CmBuilding.Name")}</Text>
                    {Util.get(item, "CmFloor.Name") && (
                        <Fragment>
                            <Text>&nbsp;</Text>
                            <Text style={{...ListStyle.rounded}}>{Util.get(item, "CmFloor.Name")}</Text>
                        </Fragment>
                    )}
                </View>
                <Text style={{...ListStyle.text}}>
                    <Text>{Util.get(item, "FirstClass.Name")}&nbsp;&nbsp;</Text>
                    {Util.get(item, "SecondClass.Name") && (
                        <Fragment>
                            <RightArrow /><Text>&nbsp;&nbsp;{Util.get(item, "SecondClass.Name")}&nbsp;&nbsp;</Text>
                        </Fragment>
                    )}
                    {Util.get(item, "ThirdClass.Name") && (
                        <Fragment>
                            <RightArrow /><Text>&nbsp;&nbsp;{Util.get(item, "ThirdClass.Name")}</Text>
                        </Fragment>
                    )}
                </Text>
                <Text style={{...ListStyle.textLight}}>
                    {item.Name}
                </Text>
                <Text style={{...ListStyle.textGray}}>
                    {item.Manufacturer} {item.FacilityCapacity}
                </Text>
            </View>
            <View style={{marginRight:15}}>
            {checked ? (
                <Icon iconFamily="MaterialCommunityIcons" iconName="checkbox-marked" size={35} color="#3b86ff" />
            ): (
                <Icon iconFamily="MaterialCommunityIcons" iconName="checkbox-blank-outline" size={35} color="#3b86ff" />
            )}
            </View>
        </TouchableOpacity>
    )
}

// list and search
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({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 [searchForm, setSearchForm] = useState({
        FirstClassId: '',
        SecondClassId: '',
        ThirdClassId: '',
    });

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

    // header button handler
    const actionHandler = (action, parameter = {}) => {
        const actions = {
            close: () => {
                console.log('close...');
                popup.close();
            },
            addSelected: () => {
                if(checkedItems.current.length == 0) {
                    Alert.alert("추가할 설비를 선택하세요.");
                    return;
                }
                popup.select(checkedItems.current);
            }
        }
        actions[action]();
    }

    const itemCheckedChange = (item, checked) => {
        if(checked) {
            if(checkedItems.current.indexOf(item) == -1) {
                checkedItems.current.push(item);
            }
        } else {
            const index = checkedItems.current.indexOf(item);
            if(index != -1) {
                checkedItems.current.splice(index, 1);
            }
        }
    }

    return (
        <PopupLayout title="설비추가" header={Header} actionHandler={actionHandler}>
            <Container>
                <SearchList page={page} pages={pages.current} setPage={setPage} refreshing={refreshing}
                    data={list} keyExtractor={item => item.FacilityCode+''} renderItem={({ item, index }) => {
                        return (
                            <Item item={item} index={index} onChecked={itemCheckedChange} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            </Container>

            <Search id="facility-popup" api={`api/app/Facility?siteId=${siteId}`} 
                    page={page} setPage={setPage} limit={50} filters={filters} sort={{field:'FacilityCode', order:'desc'}}
                    onStart={start} onSuccess={success} onFailure={fail} >
                <Fragment>
                    <SearchTitle title="시설분류" />
                    <EntitySelect style={{ marginBottom:5 }} entity="FmsFacilityCodeClass" defaultLabel="분류1" emptyLabel="전체" 
                        id="FacilityClassId" name="Name" where={`ParentFacilityClassId IS NULL`} useCheck={true}
                        onChange={(item) => { 
                            setSearchForm({...searchForm,
                                FirstClassId: item.value,
                                SecondClassId: '',
                                ThirdClassId: '',
                            });
                            filterValue([filters, setFilters], 'FirstClassId', item.value, 'eq');
                        }} />
                    <EntitySelect style={{ marginBottom:5 }} entity="FmsFacilityCodeClass" defaultLabel="분류2" emptyLabel="전체" 
                        id="FacilityClassId" name="Name" where={`ParentFacilityClassId = '${searchForm.FirstClassId}'`} useCheck={true}
                        onChange={(item) => { 
                            setSearchForm({...searchForm,
                                SecondClassId: item.value,
                                ThirdClassId: '',
                            });
                            filterValue([filters, setFilters], 'SecondClassId', item.value, 'eq');
                        }} />
                    <EntitySelect style={{ marginBottom:20 }} entity="FmsFacilityCodeClass" defaultLabel="분류3" emptyLabel="전체" 
                        id="FacilityClassId" name="Name" where={`ParentFacilityClassId = '${searchForm.SecondClassId}'`} useCheck={true}
                        onChange={(item) => { 
                            setSearchForm({...searchForm,
                                ThirdClassId: item.value,
                            });
                            filterValue([filters, setFilters], 'ThirdClassId', item.value, 'eq');
                        }} />

                    <SearchTitle title="시설명칭" />
                    <Input style={{ marginBottom:20 }} placeholder="시설명칭" small onChangeText={value => filterValue([filters, setFilters], 'Name', value, 'cn')} />

                    <SearchTitle title="설치위치" />
                    <EntitySelect style={{ marginBottom:5 }} entity="CmBuilding" siteId={siteId} defaultLabel="빌딩" emptyLabel="전체" useCheck={true}
                        onChange={(item) => { 
                            setSearchForm({...searchForm,
                                BuildingId: item.value,
                                FloorId: '',
                            });
                            filterValue([filters, setFilters], 'BuildingId', item.value, 'eq');
                        }} />
                    <EntitySelect style={{ marginBottom:5 }} entity="CmFloor" siteId={siteId} defaultLabel="층" emptyLabel="전체" 
                        where={`BuildingId = '${searchForm.BuildingId}'`}
                        onChange={(item) => { 
                            setSearchForm({...searchForm,
                                FloorId: item.value,
                            });
                            filterValue([filters, setFilters], 'FloorId', item.value, 'eq');
                        }} />
                        
                    <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>
            <PrimaryButton onPress={() => { callAction('addSelected') }}>선택추가</PrimaryButton>
            <DefaultButton onPress={() => { callAction('close') }}>닫기</DefaultButton>
            <SearchBoxIcon style={{marginLeft:5}} id="facility-popup" />
        </Fragment>
    )
}
