import React, { Fragment, useState, useEffect, useCallback, createRef, useRef } from 'react';
import { View, Text, Alert, FlatList, StyleSheet, TouchableOpacity,Animated } 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 } 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 fetchGet, { fetchPost, fetchDelete  } from '~/Utils/fetch';
import Input from '~/Components/UIControls/Input';
import Form from '~/Components/Form';
import { Util } from '~/Utils/utils';
import GradientGraph from '~/Components/UIControls/GradientGraph';
import { Selectbox } from '~/Components/UIControls/Selectbox';
import { useAuth } from '~/Components/Hooks';
// 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, "Date.Date")}
          </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 [maxValue, setMaxValue] = useState(0);

  const siteId = navigation.getParam('siteId', '')
  const facilityTypeId = navigation.getParam('facilityTypeId', '')
  const facilityCode = navigation.getParam('facilityCode', '')
  const propertyId = navigation.getParam('propertyId', '')
  const startDate = navigation.getParam('sDate', '')
  const endDate = navigation.getParam('eDate', '')
  const { auth } = useAuth(navigation);
  const { showMessage } = useToast();

  const [title,setTitle] = useState();
  useEffect(() => {
    (async () => {
      await session.load(); 
      setReady(true);
    })();
  }, []);

  const refreshList = () => {
    setPage('refresh-' + Math.random());
  }
 // search
 const fetch = async () => {
  const apiUri = `api/app/FacilityTime/Detail?siteId=${siteId}&facilityTypeId=${facilityTypeId}&propertyId=${propertyId}&facilityCode=${facilityCode}&sDate=${startDate}&eDate=${endDate}`;
  await session.load();
    try {
      const result = await fetchGet(apiUri);
      console.log(result);
      setList(result.list);
      setMaxValue(result.maxValue);
      setTitle(result.name);
    } catch (error) {
      showMessage(error.message);
    }
 };
  return ready ? (
    <BottomTabBarLayout>      
      <SearchListContainer>
        <Text style={{...ListStyle.textMediumLarge,marginLeft:15,marginTop:15}}>{title}</Text>
        <SearchList page={1} pages={1} setPage={setPage}
          data={list} renderItem={({ item, index }) => {
            return (
              <Item item={item} index={index} maxValue={maxValue} />
            )
          }}
          ListEmptyComponent={<EmptyView list={list} />}
        />
       
      </SearchListContainer>
      <Search id="energydetail" 
        page={page} limit={100} filters={filters} sort={{field:'DateTime', order:'desc'}}
        setPage={setPage} onSearch={()=>{
          fetch();
        }} >
      </Search>
    </BottomTabBarLayout>
  ) : null;
};

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

export default Screen;
