import React, { Component } from 'react';
import {
  View,
  TextInput,
  TouchableOpacity,
  Text,
  FlatList,
  Image,
  Modal,
  BackHandler,
  RefreshControl,
  Platform
} from 'react-native';
import styles from './styles/BookRequestListStyle';
import Icon from 'react-native-vector-icons/AntDesign';
import Colors from './../../../theme/Colors';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {
  Header,
  Container,
  ShadowView,
  Button,
  TouchableOpacity as TouchableOpacityNew,
  Content,
  NoRecords,
  Loader
} from '../../../components';
import IconAnt from 'react-native-vector-icons/AntDesign';
import {
  getBookRequestColor,
  getBookRequestStatus
} from './../../../libs/Utils';
import { Images } from './../../../theme';
import {
  bookRequestListRequest,
  bookRequestDetailsRequest,
  hideEditModalRequest,
  hideDeleteModalRequest,
  editBookRequestRequest,
  deleteBookRequestRequest,
  showDeleteModalRequest
} from './../../../actions';

export interface Props {
  navigation: any;
  loading: boolean;
  cheque: any;
  bookRequestList: any;
  getBookRequestList: any;
  bookRequestListLoading: any;
  getBookRequestDetails: any;
  bookRequestDetails: any;
  editModalVisible: any;
  hideEditModal: any;
  editBookRequest: any;
  hideDeleteModal: any;
  deleteModalVisible: any;
  deleteBookRequest: any;
  showDeleteModal: any;
}
interface State {
  showEditBookRequestModal: boolean;
  showDeleteBookRequestModal: boolean;
  searchText: any;
  bookName: any;
  isbnNo: any;
  edition: any;
  isPaperBack: any;
  selectedDeleteBook: any;
  bookRequestDetails: any;
  status: any;
  selectedId: any;
  selectedBook: any;
  listLoadingState: boolean;
}
class BookRequestList extends Component<Props, State> {
  constructor(props: any) {
    super(props);
    this.state = {
      showEditBookRequestModal: false,
      showDeleteBookRequestModal: false,
      selectedDeleteBook: {},
      searchText: '',
      bookName: '',
      isbnNo: '',
      edition: '',
      isPaperBack: true,
      status: null,
      selectedId: null,
      bookRequestDetails: {},
      selectedBook: {},
      listLoadingState: true
    };
  }

  componentDidMount = () => {
    BackHandler.addEventListener('hardwareBackPress', this.backHandler);
    const { getBookRequestList } = this.props;
    getBookRequestList();
    setTimeout(() => this.setState({ listLoadingState: false }), 3000);
  };

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

  shouldComponentUpdate = (nextProps: any) => {
    const { bookRequestDetails } = this.props;
    if (bookRequestDetails !== nextProps.bookRequestDetails) {
      this.setState({ bookRequestDetails: nextProps.bookRequestDetails || {} });
      const newbookRequestDetails = nextProps.bookRequestDetails;
      if (newbookRequestDetails.book_name) {
        this.setState({
          bookName: newbookRequestDetails.book_name,
          isbnNo: newbookRequestDetails.isbn,
          edition: newbookRequestDetails.edition,
          isPaperBack: newbookRequestDetails.format === 2,
          status: newbookRequestDetails.status,
          selectedId: newbookRequestDetails.id,
          selectedDeleteBook: newbookRequestDetails,
          selectedBook: newbookRequestDetails
        });
      }
    }
    return true;
  };

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

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

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

    getBookRequestList(res.trim().length > 0 && params);
  };

  editBookRequestPress = () => {
    const { editBookRequest, hideEditModal } = this.props;
    const { searchText } = this.state;
    const {
      bookName,
      isbnNo,
      edition,
      isPaperBack,
      status,
      selectedId,
      selectedBook
    } = this.state;
    let filterParams = {
      search: searchText,
      search_by_book: 1
    };
    let params = {
      id: selectedBook.id,
      book_name: bookName,
      isbn: isbnNo,
      edition,
      status,
      format: isPaperBack ? 2 : 1
    };
    hideEditModal();
    editBookRequest(params, searchText.trim().length > 0 && filterParams);
  };

  editBookRequestModal = () => {
    const { bookName, isbnNo, edition, isPaperBack } = this.state;
    const { editModalVisible, hideEditModal } = this.props;
    return (
      <Modal
        visible={editModalVisible}
        transparent={true}
        animationType={'slide'}
        onRequestClose={() => hideEditModal()}>
        <Content
          contentContainerStyle={{ backgroundColor: Colors.transparent }}>
          <TouchableOpacity
            activeOpacity={1}
            style={styles.modalContainer}
            onPress={() => hideEditModal()}>
            <TouchableOpacity
              style={styles.modalInnerContainer}
              activeOpacity={1}>
              <View style={styles.modalCircleView}>
                <Image
                  source={Images.edit}
                  style={styles.modalCircleEditImage}
                />
              </View>
              <TouchableOpacity
                onPress={() => hideEditModal()}
                style={styles.DeleteImageiew}>
                <Image source={Images.deleteBlack} style={styles.DeleteImage} />
              </TouchableOpacity>

              <View style={styles.editReqView}>
                <Text style={styles.editBookReqTitle}>Book Name:</Text>
                <View style={styles.editReqInnerView}>
                  <Image source={Images.book} style={styles.bookImage} />
                  <TextInput
                    style={styles.editBookReqValue}
                    value={bookName}
                    onChangeText={res => this.setState({ bookName: res })}
                  />
                </View>
              </View>
              <View style={styles.editReqView}>
                <Text style={styles.editBookReqTitle}>ISBN No.:</Text>
                <View style={styles.editReqInnerView}>
                  <Image source={Images.isbn} style={styles.isbnImage} />
                  <TextInput
                    style={styles.editBookReqValue}
                    value={isbnNo}
                    keyboardType={'numeric'}
                    returnKeyType={'done'}
                    onChangeText={res => this.setState({ isbnNo: res })}
                  />
                </View>
              </View>
              <View style={styles.editReqView}>
                <Text style={styles.editBookReqTitle}>Edition:</Text>
                <View style={styles.editReqInnerView}>
                  <Image source={Images.edit} style={styles.editionImage} />
                  <TextInput
                    style={styles.editBookReqValue}
                    value={edition}
                    onChangeText={res => this.setState({ edition: res })}
                  />
                </View>
              </View>
              <View style={styles.editReqView}>
                <Text style={styles.editBookReqTitle}>Format:</Text>
                <View style={styles.radioContainer}>
                  <TouchableOpacity
                    onPress={() => {
                      this.setState({ isPaperBack: true });
                    }}
                    style={styles.optionBtn}>
                    <Image
                      style={styles.radioImg}
                      source={
                        !isPaperBack ? Images.radio : Images.radioSelected
                      }
                    />
                    <Text style={styles.radioTxt}>{'Paperback'}</Text>
                  </TouchableOpacity>
                  <TouchableOpacity
                    onPress={() => {
                      this.setState({ isPaperBack: false });
                    }}
                    style={styles.optionBtn}>
                    <Image
                      style={styles.radioImg}
                      source={isPaperBack ? Images.radio : Images.radioSelected}
                    />
                    <Text style={styles.radioTxt}>{'Hardcover'}</Text>
                  </TouchableOpacity>
                </View>
              </View>
              <View style={styles.editModalButtonContainer}>
                <TouchableOpacity
                  style={styles.saveBtn}
                  onPress={() => this.editBookRequestPress()}>
                  <Text style={styles.saveBtnTxt}>Save</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.cancelBtn}
                  onPress={() => hideEditModal()}>
                  <Text style={styles.cancelBtnTxt}>Cancel</Text>
                </TouchableOpacity>
              </View>
            </TouchableOpacity>
          </TouchableOpacity>
        </Content>
      </Modal>
    );
  };

  deleteBookRequestModal = () => {
    const { selectedDeleteBook, selectedBook, searchText } = this.state;
    const {
      deleteModalVisible,
      hideDeleteModal,
      deleteBookRequest
    } = this.props;
    return (
      <Modal
        visible={deleteModalVisible}
        transparent={true}
        animationType={'slide'}
        onRequestClose={() => hideDeleteModal()}>
        <Content
          contentContainerStyle={{ backgroundColor: Colors.transparent }}>
          <TouchableOpacity
            activeOpacity={1}
            style={styles.modalContainer}
            onPress={() => hideDeleteModal()}>
            <TouchableOpacity
              style={styles.modalDeleteInnerContainer}
              activeOpacity={1}>
              <View style={styles.modalCircleView}>
                <Image
                  source={Images.deleteRed}
                  style={styles.modalCircleDeleteImage}
                />
              </View>

              <TouchableOpacity
                onPress={() => hideDeleteModal()}
                style={styles.DeleteImageiew}>
                <Image source={Images.deleteGrey} style={styles.DeleteImage} />
              </TouchableOpacity>

              <Text style={styles.deleteTxt}>
                {'Are you sure you want\n'}
                {'to delete "'}
                {
                  <Text style={styles.deleleBookTxt}>
                    {selectedBook.book_name}
                  </Text>
                }
                {'" ?'}
              </Text>

              <View style={styles.editModalButtonContainer}>
                <TouchableOpacity
                  style={styles.modalDeleteBtn}
                  onPress={() => {
                    let params = { id: selectedBook.id };
                    let filterParams = {
                      search: searchText,
                      search_by_book: 1
                    };
                    hideDeleteModal();
                    deleteBookRequest(
                      params,
                      searchText.trim().length > 0 && filterParams
                    );
                  }}>
                  <Text style={styles.saveBtnTxt}>Delete</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.cancelBtn}
                  onPress={() => hideDeleteModal()}>
                  <Text style={styles.cancelBtnTxt}>Cancel</Text>
                </TouchableOpacity>
              </View>
            </TouchableOpacity>
          </TouchableOpacity>
        </Content>
      </Modal>
    );
  };

  renderItem = ({ item, index }: any) => {
    const { getBookRequestDetails, showDeleteModal } = this.props;
    const { searchText } = this.state;
    return (
      <TouchableOpacity
        style={styles.item}
        onPress={() => {
          let params = {
            search: searchText,
            search_by_book: 1
          };
          getBookRequestDetails(item.id, true, false, params);
        }}>
        <Text style={styles.itemTitle}>{item.book_name}</Text>
      <View style={styles.flexDirection}>
        <Text style={styles.itemIsbnNOTitle}>ISBN No. : </Text>
        <Text style={styles.itemSubTitle}>{item.isbn}</Text>
        </View>
        <View style={styles.itemBottomView}>
          <Text
            style={[
              styles.statusTxt,
              { color: getBookRequestColor(item.status) }
            ]}>
            {getBookRequestStatus(item.status)}
          </Text>
  
          <View style={styles.editDelBtnContainer}>
            {item.status === 0 && (
              <TouchableOpacity
                style={styles.editBtn}
                onPress={() => getBookRequestDetails(item.id, false, true)}>
                <Image source={Images.editWhite} style={styles.editIcon} />
              </TouchableOpacity>
            )}
            <TouchableOpacity
              style={styles.deleteBtn}
              onPress={() => {
                this.setState({
                  selectedBook: item
                });
                showDeleteModal();
              }}>
              <Image source={Images.deleteWhite} style={styles.deleteIcon} />
            </TouchableOpacity>
          </View>
        </View>
      </TouchableOpacity>
    );
  };

  render() {
    const {
      bookRequestList,
      navigation,
      bookRequestListLoading,
      loading
    } = this.props;
    const { searchText, listLoadingState } = this.state;
    return (
      <>
        <Container
          transparentStatusBar
          safeAreaView={Platform.OS === 'ios' ? true : false}>
          <Header
            title={'Book Request'}
            hasBackBtn
            isWhiteBackBtn
            navigation={this.props.navigation}
          />
          <View style={styles.topButtonContainer}>
            <ShadowView shadowRadius={18}>
              <View style={styles.searchView}>
                <Icon name="search1" style={styles.searchIcon} />
                <TextInput
                  value={searchText}
                  numberOfLines={1}
                  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>
            </ShadowView>
            <Button
              style={styles.newBookReqBtn}
              title={'New Book Request'}
              titleStyle={styles.addNewReqBtnTxt}
              onPress={() => {
                let params = {
                  search: searchText,
                  search_by_book: 1
                };

                navigation.navigate('NewBookRequest', { params });
              }}
            />
          </View>
          
          <FlatList
            style={styles.flatList}
            showsVerticalScrollIndicator={false}
            data={bookRequestList || []}
            refreshControl={
              <RefreshControl
                refreshing={listLoadingState || bookRequestListLoading}
              />
            }
            ListEmptyComponent={
              !bookRequestListLoading ? <NoRecords /> : <View />
            }
            renderItem={({ item, index }) => this.renderItem({ item, index })}
            ItemSeparatorComponent={() => (
              <Image style={styles.separatorImg} source={Images.separator} />
            )}
            keyExtractor={(item, index) => index.toString()}
          />
          {this.editBookRequestModal()}
          {this.deleteBookRequestModal()}
        </Container>
        <Loader show={loading} />
      </>
    );
  }
}
function mapStateToProps({ book }: any) {
  return {
    bookRequestList: book.bookRequestList || [],
    bookRequestListLoading: book.bookRequestListLoading || false,
    bookRequestDetails: book.bookRequestDetails || {},
    editModalVisible: book.editModalVisible || false,
    deleteModalVisible: book.deleteModalVisible || false,
    loading: book.loading || false
  };
}

function mapDispatchToProps(dispatch: any) {
  return bindActionCreators(
    {
      getBookRequestList: bookRequestListRequest,
      getBookRequestDetails: bookRequestDetailsRequest,
      hideEditModal: hideEditModalRequest,
      hideDeleteModal: hideDeleteModalRequest,
      showDeleteModal: showDeleteModalRequest,
      editBookRequest: editBookRequestRequest,
      deleteBookRequest: deleteBookRequestRequest
    },
    dispatch
  );
}

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