import React from 'react';
import PropTypes from 'prop-types';
import {
  ScrollView,
  Image,
  Text,
  View,
  Dimensions,
  TouchableOpacity,
  Linking,
} from 'react-native';
import {Card} from 'react-native-elements';
import {connect} from 'react-redux';
import Screen from '../../components/Screen';
import {companiesGetById} from '../../shared/actions/companies';
import {routesGetForGroup} from '../../shared/actions/routes';
import {bindActionCreators} from 'redux';
import {categoriesGetAll} from '../../shared/actions/categories';
import MapView, {Marker} from 'react-native-maps';
import HTML from 'react-native-render-html';
import facebook from '../../assets/images/facebook.png';
import linkedin from '../../assets/images/linkedin.png';
import instagram from '../../assets/images/instagram.png';
import Icon from 'react-native-vector-icons/FontAwesome';

class CompanyDetailScreen extends Screen {
  mapRef = null;
  state = {
    marker: [],
    query: '',
  };

  componentDidMount() {
    this.props.companiesGetById(
      this.props.event.organisation.id,
      this.props.event.id,
      this.props.company.id,
    );
  }

  componentDidUpdate(oldState) {
    // Refactor to getDerivedStateFromProps
    if (this.props.company.id !== oldState.company.id) {
      this.props.companiesGetById(
        this.props.event.organisation.id,
        this.props.event.id,
        this.props.company.id,
      );
      this.props.navigation.setParams({title: this.props.company.name});
    }

    if (this.props.company.address !== oldState.company.address) {
      const marker = this.getMarker();
      const coordinates = this.props.company.address.position.coordinates;
      this.setState({marker: marker});

      setTimeout(() => {
        if (this.mapRef) {
          this.mapRef.animateCamera(
            {
              latitude: coordinates[1],
              longitude: coordinates[0],
            },
            500,
          );
        }
      }, 500);
    }
  }

  getMarker() {
    const {company} = this.props;
    const coordinates = company.address.position.coordinates;
    return (
      <Marker
        coordinate={{
          latitude: coordinates[1],
          longitude: coordinates[0],
        }}
      />
    );
  }

  openWebsite(url) {
    Linking.openURL(url);
  }

  urlify(url) {
    return url.includes('http://') ||
      url.includes('https://') ||
      url.includes('mailto://')
      ? url
      : 'https://' + url;
  }

  renderCategory(category) {
    return (
      <View key={category.id} style={{flexDirection: 'row', marginTop: 6}}>
        <View
          style={{
            height: 16,
            width: 6,
            backgroundColor: category.color,
            marginRight: 4,
          }}
        />
        <Text style={{fontSize: 11}}>{category.name}</Text>
      </View>
    );
  }

  render() {
    const {company} = this.props;
    let info = company.info || '<em>Geen informatie beschikbaar</em>';
    const regex = /<([a-z]+)\ [^>]+>/gi;
    info = info.replace(regex, '<$1>');

    return (
      <ScrollView style={{flex: 1}}>
        {company ? (
          <View style={{marginBottom: 30}}>
            <View
              style={{
                backgroundColor: 'white',
                borderWidth: 0.5,
                borderColor: '#ddd',
                borderRadius: 3,
                marginHorizontal: 15,
                marginTop: 15,
                paddingHorizontal: 10,
                paddingBottom: 5,
                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>
              )}
              {company.logo ? (
                <Image
                  style={{flex: 1, height: 200, margin: 20}}
                  resizeMode="contain"
                  source={{uri: company.logo}}
                />
              ) : null}
              <Text
                style={{textAlign: 'center', fontWeight: 'bold', fontSize: 18}}>
                {company.name}
              </Text>
            </View>
            <Card title={'Contactgegevens'}>
              {company.address ? (
                <View>
                  <Text style={{fontWeight: 'bold', marginTop: 10}}>Adres</Text>
                  <Text>
                    {company.address.street} {company.address.number}
                    {company.address.numberAddition}
                  </Text>
                  <Text>
                    {company.address.postcode} {company.address.city}
                  </Text>
                </View>
              ) : null}

              <Text style={{fontWeight: 'bold', marginTop: 10}}>
                Telefoonnummer
              </Text>
              <Text>{company.phoneNumber || '-'}</Text>

              {company.website ? (
                <View>
                  <Text style={{fontWeight: 'bold', marginTop: 10}}>
                    Website
                  </Text>
                  <TouchableOpacity
                    onPress={() =>
                      this.openWebsite(this.urlify(company.website))
                    }>
                    <Text style={{color: '#008cd6'}}>
                      {company.website || '-'}
                    </Text>
                  </TouchableOpacity>
                </View>
              ) : null}

              {company.email ? (
                <View>
                  <Text style={{fontWeight: 'bold', marginTop: 10}}>
                    E-mailadres
                  </Text>
                  <TouchableOpacity
                    onPress={() => this.openWebsite(`mailto:${company.email}`)}>
                    <Text style={{color: '#008cd6'}}>
                      {company.email || '-'}
                    </Text>
                  </TouchableOpacity>
                </View>
              ) : null}

              <Text style={{fontWeight: 'bold', marginTop: 10}}>
                Aantal medewerkers
              </Text>
              <Text>{company.employees || '-'}</Text>

              <Text style={{fontWeight: 'bold', marginTop: 10}}>Sector</Text>
              <Text>{company.sector || '-'}</Text>

              {company.facebook || company.instagram || company.linkedin ? (
                <View>
                  <Text
                    style={{
                      fontWeight: 'bold',
                      marginTop: 10,
                      marginBottom: 4,
                    }}>
                    Social Media
                  </Text>

                  <View style={{flexDirection: 'row'}}>
                    {company.facebook ? (
                      <TouchableOpacity
                        onPress={() =>
                          this.openWebsite(this.urlify(company.facebook))
                        }>
                        <Image
                          source={facebook}
                          style={{width: 25, height: 25, marginRight: 5}}
                        />
                      </TouchableOpacity>
                    ) : null}

                    {company.instagram ? (
                      <TouchableOpacity
                        onPress={() =>
                          this.openWebsite(this.urlify(company.instagram))
                        }>
                        <Image
                          source={instagram}
                          style={{width: 25, height: 25, marginRight: 5}}
                        />
                      </TouchableOpacity>
                    ) : null}

                    {company.linkedin ? (
                      <TouchableOpacity
                        onPress={() =>
                          this.openWebsite(this.urlify(company.linkedin))
                        }>
                        <Image
                          source={linkedin}
                          style={{width: 25, height: 25}}
                        />
                      </TouchableOpacity>
                    ) : null}
                  </View>
                </View>
              ) : null}
            </Card>
            <Card title={'Informatie'}>
              <HTML
                html={info}
                imagesMaxWidth={Dimensions.get('window').width}
              />
            </Card>
            {company.recommendedCourses &&
            company.recommendedCourses.length > 0 &&
            company.recommendedStudies &&
            company.recommendedStudies.length > 0 ? (
              <Card title={'Opleiding'}>
                {company.recommendedCourses &&
                company.recommendedCourses.length > 0 ? (
                  <View>
                    <Text style={{fontWeight: 'bold', marginTop: 10}}>
                      Keuzevakken
                    </Text>
                    <Text style={{marginBottom: 10}}>
                      Om bij ons te werken zijn de volgende keuzevakken
                      belangrijk:
                    </Text>
                    <Text>- {company.recommendedCourses.join('\n- ')}</Text>
                  </View>
                ) : null}

                {company.recommendedStudies &&
                company.recommendedStudies.length > 0 ? (
                  <View style={{marginTop: 10}}>
                    <Text style={{fontWeight: 'bold', marginTop: 10}}>
                      Vervolgopleidingen
                    </Text>
                    <Text style={{marginBottom: 10}}>
                      Na het behalen van je diploma zou je kunnen kiezen voor
                      een van deze vervolgstudies:
                    </Text>
                    <Text>- {company.recommendedStudies.join('\n- ')}</Text>
                  </View>
                ) : null}
              </Card>
            ) : null}
            <Card title={'Profielen'}>
              <Text>Dit bedrijf is ingedeeld in de profielen:</Text>
              {company.categories
                ? company.categories.map(category =>
                    this.renderCategory(category),
                  )
                : null}
            </Card>
            <Card title={'Locatie'}>
              <MapView
                ref={ref => {
                  this.mapRef = ref;
                }}
                initialRegion={{
                  latitude: 51.765,
                  longitude: 5.51806,
                  latitudeDelta: 0.08,
                  longitudeDelta: 0.08,
                }}
                style={{height: 300}}>
                {this.state.marker}
              </MapView>
            </Card>
            {company.images && company.images.length > 0 ? (
              <Card title={"Foto's"}>
                {company.images.map(img => (
                  <Image
                    key={img.id}
                    style={{height: 200, marginBottom: 10}}
                    source={{uri: img.filename}}
                  />
                ))}
              </Card>
            ) : null}
          </View>
        ) : null}
      </ScrollView>
    );
  }
}

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

const mapStateToProps = state => {
  return {
    auth: state.auth,
    company: state.companies.shownCompany,
    loading: state.companies.loading,
    event: state.auth.permissions ? state.auth.permissions.events[0] : null,
  };
};

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

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