import React, { Component } from 'react';
import {
  View,
  TextInput,
  TouchableOpacity,
  Text,
  FlatList,
  Image,
  RefreshControl,
  BackHandler,
  Platform
} from 'react-native';
import styles from './Styles/BookHistoryStyle';
import Icon from 'react-native-vector-icons/AntDesign';
import IconAnt from 'react-native-vector-icons/AntDesign';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {
  bookHistoryRequest,
  bookUnreserveRequest,
  bookHistoryDetailsRequest
} from './../../../actions/BookAction';
import { Header, Container, Loader, ImageX } from '../../../components';
import { Colors, Images } from './../../../theme';
import { getColor, getStatus } from './../../../libs/Utils';
import { ApiConfig } from './../../../config';

export interface Props {
  navigation: any;
  loading: boolean;
  bookHistory: any;
  bookHistoryList: any;
  bookHistoryListLoading: any;
  bookUnreserve: any;
  bookHistoryDetails: any;
}
interface State {
  searchText: any;
  currentTime: any;
}

class BookHistoryScreen extends Component<Props, State> {
  constructor(props: any) {
    super(props);
    this.state = {
      searchText: '',
      currentTime: new Date().getTime()
    };
  }

  componentDidMount = () => {
    BackHandler.addEventListener('hardwareBackPress', this.backHandler);
    const { bookHistory } = this.props;
    bookHistory();
  };

  componentWillUnmount = () => {
    BackHandler.removeEventListener('hardwareBackPress', this.backHandler);
  };

  backHandler = () => {
    const { navigation } = this.props;
    return navigation.goBack();
  };

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

    this.setState({ searchText: res });
    // if (res.length % 2 !== 0) return;
    let params = {
      search: res,
      search_by_book: 1
    };
    bookHistory(res.trim().length > 0 && params);
  };

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

  renderItem = ({ item, index }: any) => {
    const { bookUnreserve, bookHistoryDetails } = this.props;
    return (
      <TouchableOpacity
        style={styles.bookItem}
        onPress={() =>
          bookHistoryDetails(item.id, this.setCurrentTime, item.book_item_id)
        }>
        <ImageX
          source={{ uri: ApiConfig.IMG_URL + item.image }}
          defaultText={item.book_name.charAt(0)}
          style={styles.itemImg}
        />
        <View style={styles.itemDetails}>
          <Text style={styles.itemTitle} numberOfLines={2}>
            {item.book_name}
          </Text>
          <View style={styles.flexDirection}>
            <Text style={styles.itemBookIdTitle}>Book Code : </Text>
            <Text style={styles.itemSubTitle}>{item.book_code}</Text>
          </View>
          <View>
            <Text style={[styles.statusTxt, { color: getColor(item.status) }]}>
              {getStatus(item.status)}
            </Text>
          </View>
          {item.status === 1 && (
            <TouchableOpacity
              onPress={() =>
                bookUnreserve(
                  item.book_item_id,
                  this.setCurrentTime,
                  'historyList'
                )
              }
              style={styles.unreserveBtn}>
              <Text style={styles.unreserveBtnTxt}>Unreserve</Text>
            </TouchableOpacity>
          )}
        </View>
      </TouchableOpacity>
    );
  };

  render() {
    const {
      bookHistoryList,
      navigation,
      bookHistoryListLoading,
      loading
    } = this.props;
    const { searchText, currentTime } = this.state;

    return (
      <>
        <Container
          transparentStatusBar
          safeAreaView={Platform.OS === 'ios' ? true : false}>
          <Header
            navigation={navigation}
            hasBackBtn
            hasPaddingTop
            isWhiteBackBtn
            title={'Books History'}>
            <View style={styles.searchView}>
              <Icon name="search1" style={styles.searchIcon} />
              <TextInput
                value={searchText}
                style={styles.searchTxtInput}
                onChangeText={res => this.searchBook(res)}
                placeholder="Search"
                placeholderTextColor={Colors.black}
              />
              {searchText.length > 0 && (
                <TouchableOpacity
                  style={styles.closeBtn}
                  onPress={() => this.searchBook('')}>
                  <IconAnt name="close" style={styles.closeIcon} />
                </TouchableOpacity>
              )}
            </View>
          </Header>
          <FlatList
            data={bookHistoryList}
            showsVerticalScrollIndicator={false}
            extraData={bookHistoryList + currentTime}
            refreshControl={
              <RefreshControl refreshing={bookHistoryListLoading} />
            }
            keyExtractor={(item, index) => index.toString()}
            style={styles.flatList}
            ItemSeparatorComponent={() => (
              <Image style={styles.separatorImg} source={Images.separator} />
            )}
            renderItem={({ item, index }) => this.renderItem({ item, index })}
          />
        </Container>
        <Loader show={loading} />
      </>
    );
  }
}
function mapStateToProps({ book }: any) {
  return {
    bookHistoryList: book.bookHistoryList || [],
    bookHistoryListLoading: book.bookHistoryListLoading || false,
    loading: book.loading || false
  };
}

function mapDispatchToProps(dispatch: any) {
  return bindActionCreators(
    {
      bookHistory: bookHistoryRequest,
      bookUnreserve: bookUnreserveRequest,
      bookHistoryDetails: bookHistoryDetailsRequest
    },
    dispatch
  );
}

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