import React, { Component } from 'react';
import {
  View,
  Text,
  Image,
  TextInput,
  TouchableOpacity,
  BackHandler,
  Platform
} from 'react-native';
import styles from './styles/NewBookRequestStyle';
import Colors from '../../../theme/Colors';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {
  Header,
  Container,
  Content,
  Toast,
  Loader
} from '../../../components';
import { addBookRequestRequest } from '../../../actions';
import i18n from '../../../i18n';
import { Images } from '../../../theme';

export interface Props {
  navigation: any;
  addNewBookRequest: any;
  loading: any;
}
interface State {
  bookName: any;
  isbnNo: any;
  edition: any;
  isPaperBack: any;
  filterParams: any;
}
class NewBookRequest extends Component<Props, State> {
  bookReqRefs: any = {};

  constructor(props: any) {
    super(props);
    this.state = {
      bookName: '',
      isbnNo: '',
      edition: '',
      isPaperBack: true,
      filterParams: props.navigation.state.params.params || {}
    };
  }

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

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

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

  addNewBook = () => {
    const { addNewBookRequest } = this.props;
    const { bookName, isbnNo, edition, isPaperBack, filterParams } = this.state;

    if (bookName.trim().length === 0) {
      Toast.errorBottom('Please fill the book name');
      return;
    }
    if (isbnNo.trim().length === 0) {
      Toast.errorBottom('Please fill the ISBN no.');
      return;
    }
    if (edition.trim().length === 0) {
      Toast.errorBottom('Please fill the edition');
      return;
    }

    let params = {
      book_name: bookName,
      isbn: isbnNo,
      edition,
      status: 0,
      format: isPaperBack ? 2 : 1
    };
    
    addNewBookRequest(
      params,
      filterParams &&
        filterParams.search &&
        filterParams.search.trim().length > 0 &&
        filterParams
    );
  };

  moveFocus = (key: any) => {
    let toFocus = null;
    switch (key) {
      case 'bookName':
        toFocus = this.bookReqRefs.isbnNo.focus();
        break;
      case 'isbnNo':
        toFocus = this.bookReqRefs.edition.focus();
        break;
      default:
        toFocus = null;
    }
    return toFocus;
  };

  renderInput = (key: any, value: any) => {
    {console.log('key',key)}
    return (
    
      <View style={styles.txtInputView}>
        <Text style={styles.labelTxt}>{i18n.t(`newBookRequest.${key}`)}</Text>
        <TextInput
          ref={(node: any) => {
            this.bookReqRefs[key] = node;
          }}
          key={key}
          style={styles.txtInput}
          placeholder={'Enter ' + i18n.t(`newBookRequest.${key}`)}
          returnKeyType="next"
          secureTextEntry={key === 'password' || key === 'confirmPassword'}
          placeholderTextColor={Colors.borderGrey}
          value={value}
          onChangeText={val => {
            const obj: any = {};
            obj[key] = val;
            this.setState(obj);
          }}
          keyboardType={key==='isbnNo' ? 'numeric': 'default'}
          onSubmitEditing={() => {
            this.moveFocus(key);
          }}
        />
      </View>
    );
  };

  render() {
    const { bookName, isbnNo, edition, isPaperBack } = this.state;
    const { navigation, loading } = this.props;
    return (
      <>
        <Container transparentStatusBar safeAreaView={Platform.OS==='ios'?true:false}>
          <Header
            title={'New Book Request'}
            hasBackBtn
            isWhiteBackBtn
            navigation={navigation}
          />
          <Content>
            <View style={styles.innerView}>
              {this.renderInput('bookName', bookName)}
              {this.renderInput('isbnNo', isbnNo)}
              {this.renderInput('edition', edition)}
              <View style={styles.txtInputView}>
                <Text style={styles.labelTxt}>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.buttonContainer}>
                <TouchableOpacity
                  style={styles.requestBtn}
                  onPress={() => this.addNewBook()}>
                  <Text style={styles.requestBtnTxt}>Request</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.cancelBtn}
                  onPress={() => navigation.goBack()}>
                  <Text style={styles.cancelBtnTxt}>Cancel</Text>
                </TouchableOpacity>
              </View>
            </View>
          </Content>
        </Container>
        <Loader show={loading} />
      </>
    );
  }
}

function mapStateToProps({ book }: any) {
  return {
    loading: book.loading || false
  };
}

function mapDispatchToProps(dispatch: any) {
  return bindActionCreators(
    {
      addNewBookRequest: addBookRequestRequest
    },
    dispatch
  );
}

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