import React from 'react';
import PropTypes from 'prop-types';
import {
  ScrollView,
  RefreshControl,
  Text,
  View,
  FlatList,
  Image,
  TouchableOpacity,
  Modal,
  StyleSheet,
  TouchableWithoutFeedback,
} from 'react-native';
import {FormInput, Card} from 'react-native-elements';
import {connect} from 'react-redux';
import Screen from '../../components/Screen';
import {
  companiesGetAll,
  companiesSetShown,
} from '../../shared/actions/companies';
import {routesGetForGroup} from '../../shared/actions/routes';
import {bindActionCreators} from 'redux';
import {categoriesGetAll} from '../../shared/actions/categories';
import Icon from 'react-native-vector-icons/FontAwesome';
import * as moment from 'moment/min/moment-with-locales.min';

const inactiveCategoryStyle = (category) => {
  return {
    height: 16,
    width: 16,
    borderRadius: 8,
    borderWidth: 2,
    borderColor: category.color,
    marginRight: 4,
  };
};

const activeCategoryStyle = (category) => {
  return {
    height: 16,
    width: 16,
    borderRadius: 8,
    backgroundColor: category.color,
    marginRight: 4,
  };
};

class CompaniesScreen extends Screen {
  mapRef = null;
  state = {
    marker: [],
    query: '',
    filteredCompanies: [],
    modalVisible: false,
    activeCategories: [],
  };

  componentDidMount() {
    moment.locale('nl');

    if (this.props.event) {
      this.props.companiesGetAll(
        this.props.event.organisation.id,
        this.props.event.id
      );
      this.props.categoriesGetAll(this.props.event.organisation.id);
      this.setState({
        ...this.state,
        filteredCompanies: this.props.companies,
        activeCategories: this.props.categories.map((cat) => cat.id),
      });
    }
  }

  componentDidUpdate(oldState) {
    if (this.props.companies.length !== oldState.companies.length) {
      this.setState({
        ...this.state,
        query: '',
        filteredCompanies: this.props.companies,
      });
    }
    if (this.props.categories.length !== oldState.categories.length) {
      this.setState({
        ...this.state,
        query: '',
        activeCategories: this.props.categories.map((cat) => cat.id),
      });
    }
  }

  onRefresh() {
    this.props.companiesGetAll(
      this.props.event.organisation.id,
      this.props.event.id
    );
  }

  renderCategory(category) {
    return (
      <View
        key={category.id}
        style={{height: 4, flexGrow: 1, backgroundColor: category.color}}
      />
    );
  }

  toggleCategory(categoryId) {
    if (categoryId === 'all') {
      const activeCategories = this.props.categories.map((cat) => cat.id);
      this.updateFilter(this.state.query, activeCategories);
    } else if (categoryId === 'none') {
      const activeCategories = [];
      this.updateFilter(this.state.query, activeCategories);
    } else {
      const activeCategories = this.state.activeCategories;
      const index = activeCategories.findIndex((catId) => categoryId === catId);
      if (index === -1) {
        // not found, add
        activeCategories.push(categoryId);
      } else {
        activeCategories.splice(index, 1);
      }

      this.updateFilter(this.state.query, activeCategories);
    }
  }

  renderCategoryFilter(category) {
    const isCategoryActive =
      this.state.activeCategories.findIndex(
        (catId) => category.id === catId
      ) !== -1;

    return (
      <TouchableOpacity
        key={category.id}
        onPress={() => this.toggleCategory(category.id)}>
        <View
          key={category.id}
          style={{
            flexDirection: 'row',
            marginTop: 10,
            opacity: isCategoryActive ? 1 : 0.5,
          }}>
          <View
            style={
              isCategoryActive
                ? activeCategoryStyle(category)
                : inactiveCategoryStyle(category)
            }
          />
          <Text style={{fontSize: 11}}>{category.name}</Text>
        </View>
      </TouchableOpacity>
    );
  }

  selectCompany(company) {
    this.props.companiesSetShown(company, true);
  }

  renderCompany(company) {
    const info = company.info
      ? company.info
          .trim()
          .replace(/ {2}|\t|\r\n|\n|\r/gm, '')
          .replace(/<[^>]+>/g, '')
          .slice(0, 100) + '...'
      : '';
    return (
      <TouchableOpacity onPress={() => this.selectCompany(company)}>
        <View
          style={{
            backgroundColor: 'white',
            borderWidth: 0.5,
            borderColor: '#ddd',
            borderRadius: 3,
            marginHorizontal: 15,
            marginVertical: 10,
            alignItems: 'stretch',
          }}>
          {company.isSponsor && (
            <View style={{flexDirection: 'row', justifyContent: 'flex-end'}}>
              <View
                style={{
                  backgroundColor: 'gold',
                  paddingHorizontal: 10,
                  paddingVertical: 3,
                  borderBottomLeftRadius: 5,
                  borderBottomRightRadius: 5,
                  marginRight: 50,
                }}>
                <Text style={{color: 'white'}}>
                  <Icon name={'star'} size={14} /> Sponsor
                </Text>
              </View>
            </View>
          )}
          <View style={{padding: 15}}>
            {company.logo ? (
              <Image
                style={{marginVertical: 20, marginHorizontal: 40, height: 100}}
                resizeMode="contain"
                source={{uri: company.logo}}
              />
            ) : null}
            <Text
              style={{textAlign: 'center', fontWeight: 'bold', fontSize: 18}}>
              {company.name}
            </Text>
            <Text style={{textAlign: 'center', fontSize: 11}}>{info}</Text>
          </View>
          <View style={{flexDirection: 'row'}}>
            {company.categories.map((cat) => this.renderCategory(cat))}
          </View>
        </View>
      </TouchableOpacity>
    );
  }

  updateFilter(query, activeCategories) {
    const filteredCompanies = this.props.companies.filter((c) => {
      let oneOfCategoriesActive = false;
      c.categories.forEach((cat) => {
        if (activeCategories.findIndex((ac) => ac === cat.id) !== -1) {
          oneOfCategoriesActive = true;
        }
      });
      const queryIsInName = c.name.toLowerCase().includes(query.toLowerCase());

      return oneOfCategoriesActive && queryIsInName;
    });
    this.setState({...this.state, filteredCompanies, query, activeCategories});
  }

  setModalVisible(visible) {
    this.setState({...this.state, modalVisible: visible});
  }

  render() {
    const components = (
      <>
        <View
          style={{
            flexDirection: 'row',
            flex: 1,
            justifyContent: 'space-between',
            alignItems: 'center',
            padding: 20,
          }}>
          <View style={{flexGrow: 1}}>
            <FormInput
              containerStyle={{padding: 0}}
              inputStyle={{
                borderColor: '#777',
                maxWidth: 200,
                borderBottomWidth: 1,
              }}
              defaultValue={this.state.query}
              onChangeText={(query) =>
                this.updateFilter(query, this.state.activeCategories)
              }
              placeholder={'Zoek op bedrijven...'}
            />
          </View>
          {
            <TouchableOpacity
              style={{flexGrow: 0}}
              onPress={() => this.setModalVisible(true)}>
              <View
                style={{
                  borderRadius: 20,
                  width: 40,
                  height: 40,
                  backgroundColor: '#ddd',
                  paddingTop: 10,
                  alignItems: 'center',
                }}>
                <Icon name={'filter'} size={20} />
              </View>
            </TouchableOpacity>
          }
        </View>
        {this.props.companies ? (
          <FlatList
            data={this.state.filteredCompanies.map((c) => {
              c.key = c.id;
              return c;
            })}
            renderItem={({item}) => this.renderCompany(item)}
          />
        ) : null}

        <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}}>Profielen</Text>
                      <TouchableOpacity
                        onPress={() => {
                          this.setModalVisible(!this.state.modalVisible);
                        }}>
                        <Text style={{fontSize: 26}}>&times;</Text>
                      </TouchableOpacity>
                    </View>
                    <Text style={{fontSize: 12}}>
                      Bedrijven zijn ingedeeld in verschillende profielen.
                      Hiermee kun je zoeken op het profiel dat het beste bij jou
                      past!
                    </Text>
                    <TouchableOpacity
                      key={'all'}
                      onPress={() => this.toggleCategory('all')}>
                      <View style={{flexDirection: 'row', marginTop: 10}}>
                        <View style={activeCategoryStyle({color: '#222'})} />
                        <Text style={{fontSize: 11}}>Selecteer alles</Text>
                      </View>
                    </TouchableOpacity>
                    <TouchableOpacity
                      key={'none'}
                      onPress={() => this.toggleCategory('none')}>
                      <View style={{flexDirection: 'row', marginTop: 10}}>
                        <View style={inactiveCategoryStyle({color: '#222'})} />
                        <Text style={{fontSize: 11}}>Deselecteer alles</Text>
                      </View>
                    </TouchableOpacity>
                    {this.props.categories.map((cat) =>
                      this.renderCategoryFilter(cat)
                    )}
                  </View>
                </TouchableWithoutFeedback>
              </Card>
            </View>
          </TouchableWithoutFeedback>
        </Modal>
      </>
    );

    return (
      <FlatList
        style={{flex: 1}}
        refreshControl={
          <RefreshControl
            refreshing={this.props.loading}
            onRefresh={() => this.onRefresh()}
          />
        }
        data={[]}
        renderItem={() => null}
        ListFooterComponent={components}
      />
    );
  }
}

CompaniesScreen.propTypes = {
  dispatch: PropTypes.func,
  navigation: PropTypes.object,
  auth: PropTypes.object,
};

const mapStateToProps = (state) => {
  return {
    auth: state.auth,
    companies: state.companies.list,
    categories: state.categories.list,
    loading: state.companies.loading,
    event: state.auth.permissions ? state.auth.permissions.events[0] : null,
  };
};

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

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