import React from 'react';
import PropTypes from 'prop-types';
import {
  ScrollView,
  View,
  Text,
  ActivityIndicator,
  StyleSheet,
  Modal,
  TouchableWithoutFeedback,
  TouchableOpacity,
  Platform,
  FlatList,
} from 'react-native';
import {Card} from 'react-native-elements';
import {connect} from 'react-redux';
import Screen from '../../components/Screen';
import Moment from 'moment/min/moment-with-locales';
import messaging from '@react-native-firebase/messaging';
import {
  companiesGetAll,
  companiesSetShown,
} from '../../shared/actions/companies';
import {categoriesGetAll} from '../../shared/actions/categories';
import {routesGetForGroup} from '../../shared/actions/routes';
import {bindActionCreators} from 'redux';
import moment from 'moment/min/moment-with-locales.min';
import RaisedButton from '../../components/RaisedButton';
import TimelineSection from '../../components/TimelineSection';
import RouteMapSection from '../../components/RouteMapSection';
import NavigationService from '../../shared/services/NavigationService';
import Icon from 'react-native-vector-icons/FontAwesome5';
import {showLocation} from 'react-native-map-link';
import {authSetPushNotificationToken} from '../../shared/actions/auth';
import store from '../../store';

class RouteScreen extends Screen {
  state = {
    revealed: false,
    modalVisible: false,
    modalCompany: null,
  };

  componentDidMount() {
    const event = this.props.permissions.events[0];
    this.props.routesGetForGroup(
      event.organisation.id,
      event.id,
      this.props.permissions.groups[0].id
    );

    const revealed =
      !event.revealAt ||
      moment(event.revealAt).isBefore(moment(Date.now())) ||
      this.props.permissions.groups[0].accessLevel.includes('Guide');
    this.setState({revealed});
    Moment.locale('nl');

    messaging()
      .hasPermission()
      .then((enabled) => {
        if (!enabled) {
          messaging().requestPermission();
        }
      });

    this.updateToken();
  }

  setModalVisible(visible, company) {
    if (!visible) {
      this.setState({...this.state, modalVisible: visible, modalCompany: null});
    } else {
      this.setState({
        ...this.state,
        modalVisible: visible,
        modalCompany: company,
      });
    }
  }

  checkOutCompany(company) {
    this.setModalVisible(false);
    this.props.companiesSetShown(company, 'routeCompanyDetail');
  }

  getCompanyById(companyId) {
    return this.props.route.slots
      .map((s) => s.company)
      .find((s) => s && s.id === companyId);
  }

  navigateToCompany(company) {
    const {address} = company;

    showLocation({
      latitude: address.position.coordinates[1],
      longitude: address.position.coordinates[0],
      title: Platform.select({android: null, ios: company.name}), // optional,
      dialogTitle: 'Navigeren naar bedrijf', // optional (default: 'Open in Maps')
      dialogMessage: 'Met welke app wil je dit doen?', // optional (default: 'What app would you like to use?')
      cancelText: 'Annuleren',
    });
  }

  async updateToken() {
    const pushNotificationToken = await messaging().getToken();
    if (pushNotificationToken) {
      this.props.authSetPushNotificationToken(pushNotificationToken);
    }
  }

  render() {
    const rowStyle = {
      flexDirection: 'row',
      alignItems: 'center',
      padding: 10,
    };
    const iconWrapperStyle = {
      width: 25,
    };

    if (!this.props.permissions || this.props.permissions.events.length === 0) {
      return (
        <ScrollView style={{flex: 1, padding: 50}}>
          <ActivityIndicator size={100} color={'#008cd6'} />
        </ScrollView>
      );
    }

    const color = this.props.permissions.events[0].organisation.primaryColor;

    const components = (
      <>
        {this.props.route && this.state.revealed ? (
          <RouteMapSection
            slots={this.props.route.slots.filter((s) => !s.hidden)}
            onSelectCompany={(companyId) =>
              this.setModalVisible(true, this.getCompanyById(companyId))
            }
          />
        ) : null}
        {this.props.route ? (
          <TimelineSection
            navigation={this.props.navigation}
            revealed={this.state.revealed}
            event={this.props.permissions.events[0]}
            onSelectCompany={(companyId) =>
              this.setModalVisible(true, this.getCompanyById(companyId))
            }
            slots={this.props.route.slots}
            iconColor={color}
          />
        ) : null}
        <View style={{padding: 20, paddingBottom: 50}}>
          <Text style={{marginBottom: 10, textAlign: 'center'}}>
            Zien welke bedrijven er nog meer meedoen?
          </Text>
          <RaisedButton
            onPress={() => NavigationService.navigate('companies')}
            title={'Bekijk alle bedrijven'}
          />
        </View>
        <Modal
          animationType="fade"
          transparent={true}
          visible={this.state.modalVisible}
          onRequestClose={() => {}}>
          <TouchableWithoutFeedback
            onPress={() => {
              this.setModalVisible(!this.state.modalVisible);
            }}>
            <View
              style={[
                StyleSheet.absoluteFillObject,
                {backgroundColor: 'rgba(0,0,0, 0.25)'},
              ]}>
              <Card style={{margin: 22, backgroundColor: 'white'}}>
                <TouchableWithoutFeedback onPress={() => {}}>
                  <View>
                    <View style={{flexDirection: 'row', alignItems: 'center'}}>
                      <Text
                        style={{
                          fontSize: 16,
                          flexGrow: 1,
                        }}>
                        {this.state.modalCompany
                          ? this.state.modalCompany.name
                          : ''}
                      </Text>
                      <TouchableOpacity
                        onPress={() => {
                          this.setModalVisible(!this.state.modalVisible);
                        }}>
                        <Text style={{fontSize: 26}}>&times;</Text>
                      </TouchableOpacity>
                    </View>
                    <TouchableOpacity
                      onPress={() =>
                        this.checkOutCompany(this.state.modalCompany)
                      }>
                      <View style={rowStyle}>
                        <View style={iconWrapperStyle}>
                          <Icon name={'building'} />
                        </View>
                        <Text>Bedrijf bekijken</Text>
                      </View>
                    </TouchableOpacity>
                    <TouchableOpacity
                      onPress={() =>
                        this.navigateToCompany(this.state.modalCompany)
                      }>
                      <View style={rowStyle}>
                        <View style={iconWrapperStyle}>
                          <Icon name={'route'} />
                        </View>
                        <Text>Navigeren naar bedrijf</Text>
                      </View>
                    </TouchableOpacity>
                  </View>
                </TouchableWithoutFeedback>
              </Card>
            </View>
          </TouchableWithoutFeedback>
        </Modal>
      </>
    );

    return (
      <FlatList
        data={[]}
        renderItem={() => null}
        ListFooterComponent={components}
      />
    );
  }
}

RouteScreen.propTypes = {
  dispatch: PropTypes.func,
  navigation: PropTypes.object,
  auth: PropTypes.object,
  companiesSetShown: PropTypes.func,
  authSetPushNotificationToken: PropTypes.func,
};

const mapStateToProps = (state) => {
  return {
    permissions: state.auth.permissions,
    companies: state.companies.list,
    categories: state.categories.list,
    shownCompany: state.companies.shownCompany,
    route: state.routes.route,
  };
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators(
    {
      companiesGetAll,
      categoriesGetAll,
      companiesSetShown,
      routesGetForGroup,
      authSetPushNotificationToken,
    },
    dispatch
  );
};

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