import React, { Fragment, useState, useEffect, useCallback, createRef, useRef } from 'react';
import { View, Text, Alert, ActivityIndicator, StyleSheet, TouchableOpacity } from 'react-native';
import Header from '~/Components/Layouts/Header';
import {
    Search,
    SearchIcon,
    Line,
    TextInput,
    checkFilter,
    filterValue,
    ListStyle,
    DetailIcon,
    RightArrow,
    CreateButton,
    useSearch,
    SearchTitle,
} from '~/Components/Listing/Search';
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, showMessage } from '~/Components/UIControls/Message';
import { DateTimePicker } from '~/Components/UIControls/DateTimePicker';
import Input from '~/Components/UIControls/Input';
import Form from '~/Components/Form';
import { Util } from '~/Utils/utils';
import { useAuth } from '~/Components/Hooks';
import { Selectbox } from '~/Components/UIControls/Selectbox';
import IconButton from '~/Components/UIControls/IconButton';
import { usePopup } from '~/Components/UIControls/Popup';
import CodeClassCategory from '~/Components/CodeClassCategory';

// list item
const Item = ({ item, index, onPress = () => {} }) => {
    const zebra = index % 2 == 0 ? true : false;
    return (
        <TouchableOpacity
            onPress={onPress}
            style={{
                ...ListStyle.itemContainer,
                borderTopWidth: 0,
                backgroundColor: zebra ? '#fdfdfd' : '#fff',
            }}
        >
            <View style={{ ...ListStyle.vertical }}>
                <Text style={{ ...ListStyle.textLight }}>{Util.get(item, 'Name')}</Text>
                <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.textGray }}>
                    {Util.get(item, 'Manufacturer')} {Util.get(item, 'FacilityCapacity')}
                </Text>
            </View>
            <DetailIcon />
        </TouchableOpacity>
    );
};

// list and search
const Screen = (props) => {
    const navigation = props.navigation;
    const scanWhenOpen = navigation.getParam('scanWhenOpen', false);
    const qrcode = navigation.getParam('qrcode', '');
    const [filters, setFilters] = useState({
        IsUse_eq: { field: 'IsUse', op: 'eq', value: true },
        Rfid_eq: qrcode ? { field: 'Rfid', op: 'eq', value: qrcode } : {},
    });
    const [visibleSearchForm, setVisibleSearchForm] = useState(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 [rfid, setRfid] = useState({
        checked: qrcode ? true : false,
        value: qrcode,
    });

    const [searchForm, setSearchForm] = useState({
        FirstClassId: '',
        SecondClassId: '',
        ThirdClassId: '',
    });

    const { openPopup } = usePopup();

    useEffect(() => {
        if (scanWhenOpen) {
            onAction('qrcode');
        }
    }, []);

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

    const onAction = (action) => {
        if (action == 'qrcode') {
            openPopup('/Popup/Scan/Index', {}, (result) => {
                filterValue([filters, setFilters], 'Rfid', result, 'eq', true, true);
                setRfid({ checked: true, value: result });
                setVisibleSearchForm(false);
                setVisibleSearchForm(true);
                refreshList();
            });
        }
    };

    return (
        <BottomTabBarLayout>
            <SearchListContainer>
                <SearchList
                    page={page}
                    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: userinfo.SiteId,
                                        facilityCode: item.FacilityCode,
                                        auth: auth,
                                    });
                                }}
                            />
                        );
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
                {Util.get(auth, 'Update') && (
                    <CreateButton
                        onPress={() => {
                            navigation.navigate('Form', {
                                refreshList: refreshList,
                                action: Form.CREATE,
                                siteId: userinfo.SiteId,
                                facilityCode: 0,
                                auth: auth,
                            });
                        }}
                    />
                )}
            </SearchListContainer>

            <Search
                id="facility-search"
                api={`api/app/Facility?siteId=${userinfo.SiteId}`}
                page={page}
                setPage={setPage}
                limit={50}
                filters={filters}
                sort={{ field: 'FacilityCode', order: 'desc' }}
                onStart={start}
                onSuccess={success}
                onFailure={fail}
                onAction={(action) => {
                    onAction(action);
                }}
            >
                {visibleSearchForm && (
                    <Fragment>
                        <SearchTitle title="시설분류" />
                        <CodeClassCategory
                            apiUrl={'/api/FacilityCodeClass/childs'}
                            onSelect={({ node, level }) => {
                                console.log('node.id', node.id);
                                console.log('level', level);
                                switch (level) {
                                    case 0:
                                        setFilters({
                                            ...filters,
                                            FirstClassId_eq: { field: 'FirstClassId', value: node.id, op: 'eq' },
                                            SecondClassId_eq: { field: 'SecondClassId', value: '', op: 'eq' },
                                            ThirdClassId_eq: { field: 'ThirdClassId', value: '', op: 'eq' },
                                        });
                                        break;
                                    case 1:
                                        setFilters({
                                            ...filters,
                                            FirstClassId_eq: { field: 'FirstClassId', value: '', op: 'eq' },
                                            SecondClassId_eq: { field: 'SecondClassId', value: node.id, op: 'eq' },
                                            ThirdClassId_eq: { field: 'ThirdClassId', value: '', op: 'eq' },
                                        });
                                        break;
                                    case 2:
                                        setFilters({
                                            ...filters,
                                            FirstClassId_eq: { field: 'FirstClassId', value: '', op: 'eq' },
                                            SecondClassId_eq: { field: 'SecondClassId', value: '', op: 'eq' },
                                            ThirdClassId_eq: { field: 'ThirdClassId', value: node.id, op: 'eq' },
                                        });
                                        break;
                                }
                            }}
                        />
                        <View style={{ height: 20 }} />

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

                        <SearchTitle title="QR코드" />
                        <Input
                            style={{ marginBottom: 20 }}
                            placeholder="QR코드"
                            small
                            value={rfid.value}
                            onChangeText={(value) => {
                                filterValue([filters, setFilters], 'Rfid', value, 'eq');
                                setRfid({ ...rfid, value: value });
                            }}
                        />

                        <SearchTitle title="설치위치" />
                        <EntitySelect
                            style={{ marginBottom: 5 }}
                            entity="CmBuilding"
                            siteId={userinfo.SiteId}
                            defaultLabel="빌딩"
                            emptyLabel="전체"
                            useCheck={true}
                            onChange={(item) => {
                                setSearchForm({ ...searchForm, BuildingId: item.value, FloorId: '' });
                                filterValue([filters, setFilters], 'BuildingId', item.value, 'eq');
                            }}
                        />
                        <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="사용여부" />
                        <Selectbox
                            style={{ marginBottom: 20 }}
                            initialValue={true}
                            defaultLabel="사용여부"
                            emptyLabel="전체"
                            items={[
                                { label: '사용', value: true },
                                { label: '미사용', value: false },
                            ]}
                            onChange={(item) => {
                                filterValue([filters, setFilters], 'IsUse', item.value, 'eq');
                            }}
                        />
                    </Fragment>
                )}
            </Search>
        </BottomTabBarLayout>
    );
};

// header
Screen.navigationOptions = ({ navigation }) => {
    const Buttons = ({ navigation }) => {
        const { action } = useSearch('facility-search');

        return (
            <Fragment>
                <IconButton
                    iconFamily="Entypo"
                    iconName="camera"
                    style={{ marginRight: 20 }}
                    iconStyle={{ margin: 10 }}
                    size={19}
                    onPress={() => {
                        action('qrcode');
                    }}
                />
                <SearchIcon id="facility-search" />
            </Fragment>
        );
    };

    return {
        header: () => <Header navigation={navigation} title="설비정보" buttons={<Buttons navigation={navigation} />} />,
    };
};

export default Screen;
