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

//import { LinearGradient} from "expo-linear-gradient";
// list item
const Item = ({ item, index, onPress = () => { } }) => {
  const zebra = index % 2 === 0 ? true : false;
  const boxColor = item.IsSysop ? "#0B83E6" : (item.IsAllView ? "#f2335c" : (item.SiteId === 1 ? "#0b83e6" : "#0eb118"));
  return (
    <TouchableOpacity onPress={onPress} style={{ ...ListStyle.itemContainer, borderTopWidth: 0, backgroundColor: zebra ? "#fdfdfd" : "#fff" }}>
      <View style={{ ...ListStyle.horizon, flex: 1 }}>
        <Text style={{ ...ListStyle.bigRounded, borderColor: boxColor, color : boxColor  }}>
          {Util.get(item, "Name")}
        </Text>
        <View style={{ ...ListStyle.vertical,paddingLeft:10,paddingTop:4}}>
          <View style={{ ...ListStyle.horizon}}>
            {!item.IsAllView && (
            <Fragment>
              <Text style={{ ...ListStyle.text, color:boxColor, lineHeight: 18 }}>
                  {Util.get(item, "CmBusinessField.Name")}
              </Text>
              <Text style={{ ...ListStyle.textLight, textAlign: "left", paddingLeft:10, lineHeight: 18  }}>
                {Util.get(item, "Title")}
              </Text>            
            </Fragment>
            )}
            {item.IsAllView && (
            <Fragment>
              <Text style={{ ...ListStyle.textLight, textAlign: "left", lineHeight: 18  }}>
                {Util.get(item, "Title")}
              </Text>            
            </Fragment>              
            )}
          </View>
          <View style={{ ...ListStyle.horizon }}>
            <Text style={{ ...ListStyle.textGray, paddingRight: 10,  textAlign: "left", paddingTop:0, lineHeight: 15  }}>
              {Util.get(item, "CmUser.Name")}
            </Text>
            <Text style={{ ...ListStyle.textGray, textAlign: "left", paddingTop:0, lineHeight: 15  }} >
              {Util.get(item, "Date.AddDate")}
            </Text>
          </View>
        </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 [refreshing, setRefreshing] = useState(false);
  const pages = useRef(10);
  const { auth } = useAuth(navigation);
  const { showMessage } = useToast();
  //console.log('filters : ', filters);

  const isAllViewList = useRef([
    {label:'사용', value:true}, 
    {label:'미사용', value:false}
  ]);

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

  // search events...
  const start = () => {
    setRefreshing(true);
  };
  const success = (data, append) => {
    console.log('filters', filters);
    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: session.getSiteId(),
                  annId: item.AnnouncementId,
                  auth: auth,
                });
              }} />
            )
          }}
          ListEmptyComponent={<EmptyView list={list} />}
        />
        {auth.Update && <CreateButton onPress={() => {
            navigation.navigate('Form', {
                refreshList: refreshList,
                action: Form.CREATE, 
                siteId: session.getSiteId(), 
                annId: 0,
                auth : auth
            });
          }} />}
      </SearchListContainer>
      <Search id="announcement" api={`api/app/Announcement?siteId=${session.getSiteId()}&businessAuth=${auth.Business}`}
        page={page} limit={10} filters={filters} sort={{field:'AnnouncementId', order:'desc'}}
        onStart={start} onSuccess={success} onFailure={fail} setPage={setPage} >
 
        <Fragment>
          <SearchTitle title="업무분야" />
          <EntitySelect style={{ marginBottom:20 }} entity="CmBusinessField" auth={auth} defaultLabel="업무분야" emptyLabel="전체" useCheck={true}
            onChange={(item) => { 
                filterValue([filters, setFilters], 'BusinessFieldId', item.value, 'eq');
            }} />

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

          <SearchTitle title="내용" />
          <Input style={{ marginBottom:20 }} placeholder="내용" small onChangeText={value => filterValue([filters, setFilters], 'Contents', value, 'cn')} />

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

          <SearchTitle title="본사공지" />
          <Selectbox style={{ marginBottom:20 }} defaultLabel="본사공지" emptyLabel="전체"
            items={[{label:'예', value:true}, {label:'아니오', value:false}]}
            onChange={item => {
              filterValue([filters, setFilters], 'IsAllView', item.value, 'eq');
            }} />

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

// header
Screen.navigationOptions = ({ navigation }) => {
  return {
    header: () => <Header
      navigation={navigation}
      title="공지사항관리"
      buttons={<SearchIcon id="announcement" />}    />
  }
};

export default Screen;
