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 { Util } from '~/Utils/utils';
import { useAuth } from '~/Components/Hooks';

const style = StyleSheet.create({
    value : {
        width: 48,
        height: 48,
        backgroundColor: '#f5f5f5',
        borderRadius: 24,
        alignItems:'center',
        justifyContent:'center',
        marginRight: 20,
    }
});

// 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.rounded}}>{Util.get(item, "FacilityTypeName")}</Text>
                <Text style={{...ListStyle.textLight}}>
                    {Util.get(item, "FacilityName")}
                </Text>
                <Text style={{...ListStyle.textMedium}}>
                    {Util.get(item, "MonitoringPointName")}
                </Text>
                <Text style={{...ListStyle.textLight}}>
                    {Util.get(item, "CreatedDateTime").replace('T', ' ')}
                </Text>
            </View>
            <View style={style.value}>
                <Text>
                {item.CurrentValue==0?'FALSE':'TRUE'}
                </Text>
            </View>
        </TouchableOpacity>
    )
}

// list and search
const Screen = (props) => {
    const navigation = props.navigation;
    const [filters, setFilters] = useState({});
    const [list, setList] = useState(null);
    const [page, setPage] = useState(1);
    const [refreshing, setRefreshing] = useState(false);
    const [isRealtime, setIsRealtime] = useState(false);
    const pages = useRef(10);
    const { auth, userinfo } = useAuth(navigation);
    const { showMessage } = useToast();

    // load session when mount...
    useEffect(() => {
      }, []);

    useInterval(() => {
        console.log(isRealtime);
        if (isRealtime) {
            refreshList();
        }
    }, 1000 * 10); // 1분

    // 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>
            <View style={{padding:15, border:'1px solid red'}}>
            <Checkbox color="#3b86ff" label="실시간 조회" onChange={checked => {
                setIsRealtime(checked);
            }}/>
            </View>
            <SearchListContainer>
                <SearchList page={page} pages={pages.current} setPage={setPage} refreshing={refreshing}
                    data={list} renderItem={({ item, index }) => {
                        return (
                            <Item item={item} index={index} onPress={() => {
                            }} />
                        )
                    }}
                    ListEmptyComponent={<EmptyView list={list} />}
                />
            </SearchListContainer>


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

                    <SearchTitle title="시설유형" />
                    <EntitySelect style={{ marginBottom:5 }} entity="BemsFacilityType" defaultLabel="시설유형" emptyLabel="전체" 
                        onChange={(item) => {
                            filterValue([filters, setFilters], 'BemsMonitoringPoint.CmFacility.FacilityTypeId', item.value, 'eq');
                        }} />

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

                    <SearchTitle title="관제점" />
                    <Input style={{ marginBottom:20 }} placeholder="관제점" small onChangeText={value => filterValue([filters, setFilters], 'BemsMonitoringPoint.Name', value, 'cn')} />

                    <SearchTitle title="날짜" />
                    <DateTimePicker style={{ marginBottom:10 }} placeholder="시작일" useClear={true} onChange={(newDate) => {
                                filterValue([filters, setFilters], 'CreatedDateTime', Util.toDateString(newDate) + ' 00:00:00.000', 'ge');}} />
                    <DateTimePicker style={{ marginBottom:10 }} placeholder="종료일" useClear={true} onChange={(newDate) => {
                                filterValue([filters, setFilters], 'CreatedDateTime', Util.toDateString(newDate) + ' 23:59:59.998', 'le');}} />

                </Fragment>
            </Search>
        </BottomTabBarLayout> 
    );
};

// header
Screen.navigationOptions = ({navigation}) => { 
    return { 
        header: () => <Header 
            navigation={navigation} 
            title="경보상태" 
            buttons={<SearchIcon id="alarm_monitoring_point" />}
        /> 
    } 
};

export default Screen;

function useInterval(callback, delay) {
    const savedCallback = useRef();
  
    // Remember the latest callback.
    useEffect(() => {
      savedCallback.current = callback;
    }, [callback]);
  
    // Set up the interval.
    useEffect(() => {
      function tick() {
        savedCallback.current();
      }
      if (delay !== null) {
        let id = setInterval(tick, delay);
        return () => clearInterval(id);
      }
    }, [delay]);
  }