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,
    useSearch,
    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 { Util } from '~/Utils/utils';
import { useAuth } from '~/Components/Hooks';
import IconButton from '~/Components/UIControls/IconButton';
import { usePopup } from '~/Components/UIControls/Popup';

// 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 }}>
                <View style={{ ...ListStyle.horizon }}>
                    <Text style={{...ListStyle.rounded}}>{Util.get(item, 'MonitoringPointName')}</Text>
                    {Util.get(item, 'FloorName') && (
                        <>
                            <Text>&nbsp;</Text>
                            <Text style={{ ...ListStyle.rounded }}>{Util.get(item, 'FloorName')}</Text>
                        </>
                    )}
                </View>
                <Text style={{ ...ListStyle.textLight }}>{Util.get(item, 'Name')}</Text>
                <Text style={{ ...ListStyle.text }}>
                    <Text>{Util.get(item, 'FirstClassName')}&nbsp;&nbsp;</Text>
                    {Util.get(item, 'SecondClassName') && (
                        <Fragment>
                            <RightArrow />
                            <Text>&nbsp;&nbsp;{Util.get(item, 'SecondClassName')}&nbsp;&nbsp;</Text>
                        </Fragment>
                    )}
                    {Util.get(item, 'ThirdClassName') && (
                        <Fragment>
                            <RightArrow />
                            <Text>&nbsp;&nbsp;{Util.get(item, 'ThirdClassName')}</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({
        Rfid_eq: qrcode ? { field: 'Rfid', op: 'eq', value: qrcode } : {},
    });
    const [list, setList] = useState(null);
    const [page, setPage] = useState(1);
    const [visibleSearchForm, setVisibleSearchForm] = useState(true);
    const [refreshing, setRefreshing] = useState(false);
    const [rfid, setRfid] = useState({
        checked: qrcode ? true : false,
        value: qrcode,
    });

    const pages = useRef(10);
    const { auth, userinfo } = useAuth(navigation);
    const { showMessage } = useToast();

    const { openPopup } = usePopup();

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

    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,
                                        propertyId: item.PropertyId,
                                        auth: auth,
                                        userinfo: userinfo,
                                    });
                                }}
                            />
                        );
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            </SearchListContainer>

            <Search
                id="manual-meter-search"
                api={`api/app/ManualMeter?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="시설분류" />
                        <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={userinfo.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={userinfo.SiteId}
                            defaultLabel="층"
                            emptyLabel="전체"
                            where={`BuildingId = '${searchForm.BuildingId}'`}
                            onChange={(item) => {
                                setSearchForm({ ...searchForm, FloorId: item.value });
                                filterValue([filters, setFilters], 'FloorId', item.value, 'eq');
                            }}
                        />

                        <SearchTitle title="관제점" />
                        <Input
                            style={{ marginBottom: 20 }}
                            placeholder="관제점"
                            small
                            onChangeText={(value) => filterValue([filters, setFilters], 'MonitoringPointName', 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 });
                            }}
                        />
                    </Fragment>
                )}
            </Search>
        </BottomTabBarLayout>
    );
};

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

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

    return {
        header: () => <Header navigation={navigation} title="에너지 수검침" buttons={<Buttons navigation={navigation} />} />,
    };
};

export default Screen;
