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, PrimaryButton } 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';
import Button from '~/Components/UIControls/Button';
import moment from 'moment';

// list item
const Item = ({ item, index,maxValue, onPress = () => { } }) => {
  const zebra = index % 2 === 0 ? true : false;
  return (
    <View 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, "ShortDateTime")}{Util.get(item, "DayOfWeek")}
          </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={Util.getScreenWidth()-30} maxValue={maxValue} value={Util.get(item, "Value")}></GradientGraph>  
        </View>

        <View style={{ ...ListStyle.horizon, width:'100%', justifyContent:'space-between'}}>
          <Text style={{ ...ListStyle.textGrayMedium,fontSize:14 }}>
            {Util.get(item, "LastShortDateTime")}{Util.get(item, "DayOfWeek")}
          </Text>
          <Text style={{ ...ListStyle.textMedium,fontSize:14,color:'#0b83e6',paddingRight:15 }}>
            {Util.toPrice(Util.get(item, "LastValue"))}
          </Text>
        </View>
        <View style={{ ...ListStyle.horizon}}>
          <GradientGraph width={Util.getScreenWidth()-30} maxValue={maxValue} value={Util.get(item, "LastValue")}></GradientGraph>  
        </View>
      </View>
    </View>
  )
}

// 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 [analysisList, setAnalysisList] = useState([]);
  const [page, setPage] = useState(1);
  const [maxValue, setMaxValue] = useState(0);
  const [startDate,setStartDate] = useState(Util.toDateString(Util.addDate(-7)));
  const [endDate,setEndDate] = useState(Util.toDateString());
  
  const [facilityCode,setFacilityCode] = useState(1);
  const [timeType,setTimeType] = useState(0);
  const [timeTypeName,setTimeTypeName] = useState('일별');
  const [energyType,setEnergyType] = useState("");
  const [energyTypeName,setEnergyTypeName] = useState('TOE');
  const { auth, userinfo } = useAuth(navigation);
  const { showMessage } = useToast();

  const [title,setTitle] = useState('TOE 사용량(일별)');
  const searchTimeType = useRef([ 
    {label:'일별', value:'0'}, 
    {label:'월별', value:'1'}
  ]);
  const searchEnergyType = useRef([ 
    {label:'전기', value:'0'},
    {label:'가스', value:'1'},
    {label:'수도', value:'2'},
    {label:'등유', value:'3'},
    {label:'LPG', value:'4'},
    {label:'중온수', value:'5'}
  ]);  
  // load session when mount...
  useEffect(() => {
    (async () => {
      await session.load();
      setReady(true);
    })();
  }, []);

  const refreshList = () => {
    setPage('refresh-' + Math.random());
    fetch();
  }
 // search
 const fetch = async () => {
  //setLoading(true);

  const start = timeType == 1 ? moment(startDate).format('YYYY-MM') : startDate;
  const end = timeType == 1 ? moment(endDate).format('YYYY-MM') : endDate;

  const apiUri = `api/EnergyDayAnalysis/Data?siteId=${session.getSiteId()}&interval=${timeType}&type=${energyType}&startDate=${start}&endDate=${end}`;
  await session.load();
    try {
      const result = await fetchGet(apiUri);
      console.log(result);
      setList(Util.get(result, 'listGrid', []));
      setAnalysisList(Util.get(result, 'analysisGrid', []));
      setMaxValue(result.maxValue);
    } catch (error) {
      showMessage(error.message);
    }
  };
  return ready ? (
    <BottomTabBarLayout>      
      <SearchListContainer>
        <Text style={{...ListStyle.textMediumLarge,margin: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} />}
        />

        {auth.Update && (
          <CreateButton label="증감사유" style={{width:120,paddingHorizontal:20}} onPress={() => {
            navigation.navigate('Form', {
                refreshList: refreshList,
                action: Form.CREATE,
                siteId: userinfo.SiteId,
                fuelTypeId: energyType == '' ? 1 : (parseInt(energyType) + 1),
                fuelPriceId: 1,
                yearMonth: moment(endDate).format('YYYY-MM'),
                auth: auth,
                userinfo: userinfo,
            });
          }} />
        )}

      </SearchListContainer>

      {!!analysisList && analysisList.length > 0 && (
      <View style={{width:'100%'}}>
        <View style={{height:8, borderColor:'#909090', borderWidth:1, borderBottomWidth:0, borderTopLeftRadius:8, borderTopRightRadius:8}} />
        {analysisList.map((item, index) => {
          return (
            <TouchableOpacity 
              key={`analysis-item-${index}`}
              style={[
                ListStyle.itemContainer, { 
                  paddingTop:8, paddingBottom:8, justifyContent:'flex-start', borderWidth:1, borderTopWidth:0 
                }
              ]}
              onPress={() => {
                navigation.navigate('Form', {
                  refreshList: refreshList,
                  action: Form.VIEW,
                  siteId: userinfo.SiteId,
                  fuelTypeId: item.FuelTypeId,
                  fuelPriceId: item.FuelPriceId,
                  priceTypeId: item.PriceTypeId,
                  yearMonth: Util.get(item, 'YearMonth').replace(/[\.]/g, '-'),
                  auth: auth,
                  userinfo: userinfo,
                });
              }}
            >
              <View style={{flex:1,flexDirection:'row'}}>
                <Text style={{...ListStyle.rounded, marginRight:5}}>{item.YearMonth}</Text>
                <Text style={{...ListStyle.text, lineHeight:28}}>{item.SiteName}</Text>
              </View>
              <Text style={{...ListStyle.text, lineHeight:28, marginRight:15}}>{item.PriceTypeName}</Text>
            </TouchableOpacity>
          )
        })}
      </View>
      )}

      <Search id="energy" 
        page={page} limit={100} filters={filters} sort={{field:'DateTime', order:'desc'}}
        setPage={setPage} onSearch={()=>{
          setTitle(energyTypeName + ' 사용량 (' + timeTypeName + ')');
          fetch();
        }} >
 
        <Fragment>
          <Selectbox style={{ marginBottom:10,flex : 1}} initialValue={true} defaultLabel="시간별" emptyLabel="전체"
            items={searchTimeType.current}  editable={true} initialValue={'0'}
              onChange={item => {
                setTimeType(item.value);
                setTimeTypeName(item.label);
                if(item.value == 0){
                  setStartDate(Util.toDateString(Util.addDate(-7,new Date())));
                  setEndDate(Util.toDateString(new Date()));
                }else {
                  setStartDate(Util.getFirstDate(Util.addDate(-365,new Date())));
                  setEndDate(Util.getLastDate(new Date()));
                }
              }} 
            />

          <Selectbox style={{ marginBottom:10,flex : 1}} initialValue={true} defaultLabel="에너지원" emptyLabel="TOE"
            items={searchEnergyType.current}  editable={true} initialValue={''}
              onChange={item => {
                if(item.value ===""){
                  setEnergyType("");
                  setEnergyTypeName("TOE");
                }else{
                  setEnergyType(item.value);
                  setEnergyTypeName(item.label)
                }
            }} />
          <DateTimePicker style={{ marginBottom:10 }} date={startDate} placeholder="시작일" useClear={true} 
            onChange={(newDate) => {
              setStartDate(Util.toDateString(newDate));
            }} />
          <DateTimePicker style={{ marginBottom:10 }} date={endDate}  placeholder="종료일" useClear={true} 
            onChange={(newDate) => {
              setEndDate(Util.toDateString(newDate));
            }} />
        </Fragment>
      </Search>
    </BottomTabBarLayout>
  ) : null;
};

// header
Screen.navigationOptions = ({ navigation }) => {
  const Buttons = () => {
    return (
      <View style={{flexDirection:'row'}}>
        <SearchIcon id="energy" />
      </View>
    )
  }

  return {
    header: () => <Header
      navigation={navigation}
      title="에너지증감분석"
      buttons={<Buttons />}
    />
  }
};

export default Screen;
