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,FileTextIcon, 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';
import { MonthPicker } from '~/Components/UIControls/MonthPicker';

// list item
const Item = ({ item, index, onPress = () => { } }) => {
  //console.log(item);
  const zebra = index % 2 === 0 ? true : false;
  const boxColor = item.SiteId === 1 ? "#0b83e6":"#0eb118";
  return (
    <TouchableOpacity onPress={onPress} style={{ ...ListStyle.itemContainer, borderTopWidth: 0, backgroundColor: zebra ? "#fdfdfd" : "#fff" }}>
      <View style={{ ...ListStyle.vertical,width:'100%'}}>
        <View style={{ ...ListStyle.horizon,width:'100%',paddingRight:15,justifyContent:"space-between"}}>
          <View style={{flexDirection:'row'}}>
            {item.IsAllView == "Y" && (
            <Text style={{ 
              ...ListStyle.text, 
              width:80, height:30, 
              borderRadius:5, 
              textAlign:'center', 
              lineHeight:30, 
              borderWidth:1, 
              borderColor:'#0b83e6',
              color:'#0b83e6',
              marginRight:5,
            }}>
              본사공지
            </Text>
            )}
            <Text style={{ ...ListStyle.text, height:30, lineHeight:30, borderColor: boxColor }}>
              {Util.get(item, "Title")}
            </Text>
          </View>
          <FileTextIcon />
        </View>
      </View>
    </TouchableOpacity>
  )
}

// list and search
const Screen = props => {
  const navigation = props.navigation;
  const [ready, setReady] = useState(false);
  const [filters, setFilters] = useState({});
  const [list, setList] = useState(null);
  const [page, setPage] = useState(1);
  const [refreshing, setRefreshing] = useState(false);
  const pages = useRef(10);
  const [year,setYear] = useState('');
  const [month,setMonth] = useState('');
  const { auth } = useAuth(navigation);
  const { showMessage } = useToast();
  console.log('filters : ', filters);

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

  // search events...
  const start = () => {
    setRefreshing(true);
  };
  const success = (data, append) => {
    pages.current = data.pages;
    
    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());
}
  //console.log("list", list);

  return ready ? (
    <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: item.SiteId,
                  surveyId : item.SurveyId,
                  isAllView : item.IsAllView,
                  auth: auth,
                });
              }} />
            )
          }}
          ListEmptyComponent={<EmptyView list={list} />}
        />
        {auth.Update && <CreateButton onPress={() => {
            navigation.navigate('Form', {
                refreshList: refreshList,
                action: Form.CREATE, 
                siteId: session.getSiteId(),
                auth: auth,
            });
          }} />}
      </SearchListContainer>
      <Search id="survey" api={`api/Survey?siteId=${session.getSiteId()}`}
        page={page} limit={12} filters={filters} sort={{field:'Month', order:'desc'}}
        onStart={start} onSuccess={success} onFailure={fail} setPage={setPage} >
 
        <Fragment>
          <SearchTitle title="등록월" />
          <Form.MonthPicker style={{ marginBottom:20 }} placeholder="검색연월" maximumDate="9999-12" monthFormat="YYYY년 MM월" onChange={(momentValue, stringValue) => {
              filterValue([filters, setFilters], 'Year', momentValue.startOf('month').format('YYYY'), 'eq');
              filterValue([filters, setFilters], 'Month', momentValue.startOf('month').format('MM'), 'eq');
          }} />
        </Fragment>
      </Search>
    </BottomTabBarLayout>
  ) : null;
};

// header
Screen.navigationOptions = ({ navigation }) => {
  return {
    header: () => <Header
      navigation={navigation}
      title="주요설비현황"
      buttons={<SearchIcon id="survey" />}    />
  }
};

export default Screen;
