import React, { Component } from 'react';
import {
  View,
  TextInput,
  TouchableOpacity,
  Text,
  FlatList,
  Image,
  RefreshControl,
  Platform
} from 'react-native';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Icon from 'react-native-vector-icons/AntDesign';
import styles from './Styles/SearchBookStyle';
import {
  Header,
  Container,
  TouchableOpacity as TouchableOpacityNew,
  NoRecords,
  ImageX
} from '../../../components';
import ShadowView from '../../../components/ShadowView';
import IconAnt from 'react-native-vector-icons/AntDesign';
import { Images, Colors } from './../../../theme';
import { searchBookRequest } from './../../../actions';
import { ApiConfig } from './../../../config';
import { color } from 'react-native-reanimated';

export interface Props {
  navigation: any;
  searchBook: any;
  searchBookLoading: any;
  searchBookList: any;
}
interface state {
  searchByName?: boolean;
  searchText?: any;
  currentTime?: any;
}

class SearchBookScreen extends React.PureComponent<Props, state> {
  searchBookRefs: any = {};

  constructor(props: any) {
    super(props);
    this.state = {
      searchByName: true,
      searchText: '',
      currentTime: new Date().getTime()
    };
  }

  componentDidMount = () => {
    this.forceSearchBook(true);
  };

  toggleButtonDrawer = () => {
    this.props.navigation.toggleDrawer();
  };

  getColor = (status: any) => {
    let color = '';
    switch (status) {
      case 1:
        color = '#00802b';
        break;
      case 2:
        color = '#ff6666';
        break;
    }
    return color;
  };

  searchBook = (res: any) => {
    const { searchBook } = this.props;
    const { searchByName } = this.state;

    this.setState({ searchText: res });
    //if (res.length % 2 !== 0) return;
    let params = {
      search: res,
      search_by_book: searchByName ? 1 : 0
    };
    searchBook(params);
  };

  forceSearchBook = (searchByName: boolean) => {
    let { searchText } = this.state;
    const { searchBook } = this.props;

    let params = {
      search: searchText,
      search_by_book: searchByName ? 1 : 0
    };
    searchBook(params);
  };

  setCurrentTime = () => {
    this.setState({ currentTime: new Date().getTime() });
  };

  _renderItem = ({ item, index }: any) => {
    const { navigation } = this.props;
    return (
      <TouchableOpacityNew
        style={styles.item}
        onPress={() => {
          navigation.navigate('BookDetails', {
            item,
            setCurrentTime: this.setCurrentTime
          });
        }}>
        <ImageX
          source={{ uri: ApiConfig.IMG_URL + item.id + '.jpg' }}
          defaultText={item.name.charAt(0)}
          style={styles.itemImg}
        />

        <View style={styles.itemDetailsView}>
          <Text style={styles.itemTitle} numberOfLines={2}>
            {item.name}
          </Text>
          <Text style={styles.itemSubTitle}>{'Author: ' + item.authors}</Text>
          <Text style={styles.itemSubTitle}>
            {'Language: ' + item.language_name}
          </Text>
          <Text
            style={[styles.statusTxt, { color: this.getColor(item.status) }]}>
            {item.status === 1 ? 'Available' : 'Not Available'}
          </Text>
        </View>
      </TouchableOpacityNew>
    );
  };

  render() {
    const { searchByName, searchText, currentTime } = this.state;
    const { searchBookLoading, searchBookList } = this.props;
    return (
      <Container
        transparentStatusBar
        safeAreaView={Platform.OS === 'ios' ? true : false}>
        <Header
          title={'Search by'}
          hasMenuBtn
          btnPress={() => {
            this.props.navigation.navigate('DrawerOpen');
          }}
        />

        <View style={styles.radioContainer}>
          <TouchableOpacity
            onPress={() => {
              this.forceSearchBook(true);
              this.setState({ searchByName: true });
            }}
            style={styles.optionBtn}>
            <Image
              style={styles.radioImg}
              source={!searchByName ? Images.radio : Images.radioSelected}
            />
            <Text style={styles.radioTxt}>{'Book'}</Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => {
              this.forceSearchBook(false);
              this.setState({ searchByName: false });
            }}
            style={styles.optionBtn}>
            <Image
              style={styles.radioImg}
              source={searchByName ? Images.radio : Images.radioSelected}
            />
            <Text style={styles.radioTxt}>{'Author'}</Text>
          </TouchableOpacity>
        </View>

        <ShadowView
          style={styles.shadowView}
          shadowRadius={20}
          shadowColor={searchText.length > 0 && Colors.purpule}
          shadowBorder={12}>
          <View style={styles.searchView}>
           <Icon name="search1" style={styles.searchIcon} />
            <TextInput
              value={searchText}
              style={styles.searchTxtInput}
              selectionColor={Colors.theme}
              onChangeText={res => {
                this.searchBook(res);
              }}
              placeholder={
                searchByName == true ? 'Search Books' : 'Search Author'
              }
              placeholderTextColor={Colors.darkBlack}
            />
            {searchText.length > 0 && (
              <TouchableOpacity
                style={styles.closeBtn}
                onPress={() => this.searchBook('')}>
                <IconAnt name="close" style={styles.closeIcon} />
              </TouchableOpacity>
            )}
          </View>
        </ShadowView>

        <FlatList
          style={styles.flatList}
          ref={(node: any) => {
            this.searchBookRefs.searchList = node;
          }}
          refreshControl={<RefreshControl refreshing={searchBookLoading} />}
          ListEmptyComponent={!searchBookLoading ? <NoRecords /> : <View />}
          showsVerticalScrollIndicator={false}
          keyExtractor={(item, index) => index.toString()}
          data={searchBookList}
          extraData={searchBookList + currentTime}
          ItemSeparatorComponent={() => (
            <Image style={styles.separatorImg} source={Images.separator} />
          )}
          renderItem={({ item, index }) => this._renderItem({ item, index })}
        />
      </Container>
    );
  }
}

function mapStateToProps({ book }: any) {
  return {
    searchBookList: book.searchBookList || [],
    searchBookLoading: book.searchBookLoading
  };
}

function mapDispatchToProps(dispatch: any) {
  return bindActionCreators(
    {
      searchBook: searchBookRequest
    },
    dispatch
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(SearchBookScreen);
