import React, { Fragment, useState, useEffect, useCallback, createRef, useRef } from 'react';
import { View, Text, Alert, FlatList, StyleSheet, TouchableOpacity,Animated } from 'react-native';
import Header from '~/Components/Layouts/Header';
import { Search, SearchIcon, Line, TextInput, checkFilter, filterValue, ListStyle, DetailIcon, RightArrow, CreateButton } 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 } from '~/Components/UIControls/Message';
import { DateTimePicker } from '~/Components/UIControls/DateTimePicker';
import fetchGet, { fetchPost, fetchDelete  } from '~/Utils/fetch';
import { Util } from '~/Utils/utils';
import GradientGraph from '~/Components/UIControls/GradientGraph';
import { useAuth } from '~/Components/Hooks';
import { MonthPicker } from '~/Components/UIControls/MonthPicker';

// list item
const Item = ({ item, index,maxValue, 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, flex: 1 }}>
        <View style={{ ...ListStyle.horizon, width:'100%', justifyContent:'space-between'}}>
          <Text style={{ ...ListStyle.textMedium,fontSize:14 }}>
            {Util.get(item, "Name")}
          </Text>
          <Text style={{ ...ListStyle.textMedium,fontSize:14,color:'#0b83e6',paddingRight:15 }}>
            {Util.toPrice(Util.get(item, "Value"))}
          </Text>
        </View>
        <View style={{ ...ListStyle.horizon}}>
          <GradientGraph width={300} maxValue={maxValue} value={Util.get(item, "Value")}></GradientGraph>  
        </View>
      </View>
      </TouchableOpacity>
  )
}

// list and search
const Screen = props => {
  //console.log(props.navigation);
  const navigation = props.navigation;
  const [ready, setReady] = useState(false);
  const [filters, setFilters] = useState({});
  const [list, setList] = useState(null);
  const [page, setPage] = useState(1);
  const pages = useRef(10);
  const [maxValue, setMaxValue] = useState(0);
  const [startDate,setStartDate] = useState(Util.getFirstDate(new Date));
  const [endDate,setEndDate] = useState(Util.getLastDate(new Date));
  const [facilityTypeId,setFacilityTypeId] = useState(1);
  const [propertyId,setpropertyId] = useState(32);
  const [formulaId,setFormulaId] = useState(1);
  const [facilityTypeName,setFacilityTypeName] = useState('전기');
  const { auth } = useAuth(navigation);
  const { showMessage } = useToast();

  const [title,setTitle] = useState((new Date()).getFullYear() + '년 ' +((new Date()).getMonth() + 1) + '월');
  const [subTitle,setSubTitle] = useState('공조기');
  // load session when mount...
  useEffect(() => {
    (async () => {
      await session.load(); 
      setReady(true);
    })();
  }, []);

  const refreshList = () => {
    setPage('refresh-' + Math.random());
  }
 // search
 const fetch = async () => {
  const apiUri = `api/app/FacilityTime?siteId=${session.getSiteId()}&facilityTypeId=${facilityTypeId}&propertyId=${propertyId}&sDate=${startDate}&eDate=${endDate}`;
  await session.load();
    try {
      const result = await fetchGet(apiUri);
      pages.current = result.pages;
      setList(result.list);
      setMaxValue(result.maxValue);
    } catch (error) {
      showMessage(error.message);
    }
 };
  return ready ? (
    <BottomTabBarLayout>      
      <SearchListContainer>
        <Text style={{...ListStyle.textMediumLarge,marginLeft:15,marginTop:15}}>{title}</Text>
        <Text style={{...ListStyle.textMedium,marginLeft:15,marginTop:10,marginBottom:10}}>{subTitle}</Text>
        
        <SearchList page={0} pages={0} setPage={setPage}
          data={list} renderItem={({ item, index }) => {
            return (
              <Item item={item} index={index} maxValue={maxValue} onPress={() => {
                navigation.navigate('Form', {
                    refreshList: refreshList,
                    siteId: session.getSiteId(), 
                    facilityTypeId:facilityTypeId,
                    facilityCode:item.FacilityCode,
                    propertyId:propertyId,
                    sDate:startDate,
                    eDate:endDate
                });
              }} />
            )
          }}
          ListEmptyComponent={<EmptyView list={list} />}
        />
       
      </SearchListContainer>
      <Search id="energy" 
        page={page} limit={100} filters={filters} sort={{field:'DateTime', order:'desc'}}
        setPage={setPage} onSearch={()=>{
          fetch();
        }} >
 
        <Fragment>
          <EntitySelect style={{ marginBottom:10 }} entity="BemsFacilityType" defaultLabel="설비" emptyLabel="전체" where={"FacilityTypeId in (1,2,4,5,8)"} defaultValue={"1"}
            onChange={(item) => { 
                setSubTitle(item.label);
                setFacilityTypeId(item.value);
                if(item.value == "1"){
                  setpropertyId("32");
                }else if(item.value == "2"){
                  setpropertyId("17");
                }else if(item.value == "4"){
                  setpropertyId("11");
                }else if(item.value == "5"){
                  setpropertyId("10");
                }else if(item.value == "8"){
                  setpropertyId("9");
                }
            }} />

          <MonthPicker style={{ marginBottom:20 }} placeholder="검색연월" monthFormat="YYYY년 MM월" onChange={(momentValue, stringValue) => {
            setStartDate(momentValue.startOf('month').format('YYYY-MM-DD'));
            setEndDate(momentValue.endOf('month').format('YYYY-MM-DD'));
            setTitle(stringValue);
          }} />
          
        </Fragment>
      </Search>
    </BottomTabBarLayout>
  ) : null;
};

// header
Screen.navigationOptions = ({ navigation }) => {
  return {
    header: () => <Header
      navigation={navigation}
      title="에너지 사용량 조회"
      buttons={<SearchIcon id="energy" />}    />
  }
};

export default Screen;
