import React, { Component } from 'react';
import {
  StyleSheet,
  View,
} from 'react-native';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';

import { Button as BigButton, FormInput, FormLabel } from 'react-native-elements';
import RNGooglePlaces from 'react-native-google-places';
import { NavigationActions } from 'react-navigation';
import { connect, Dispatch } from 'react-redux';
import { UserActions } from '../../actions';
import { Employer, EmployerBody, RootState } from '../../models';
import { LocationInfo, PhotoArea } from '../common/';
import { Button, Card, Colors, Header } from '../ui';

interface StateProps {
  user: Employer;
  loading: boolean;
  error?: string;
}

interface DispatchProps {
  onSaveBody: (userId: string, data: EmployerBody) => void;
  onSaveImage: (userId: string, photoPath: string) => void;
  onClose: () => void;
}

interface State extends EmployerBody {
  photoPath?: string;
}

class EmployerProfileEditForm extends Component<StateProps & DispatchProps, State> {

  constructor(props: StateProps & DispatchProps) {
    super(props);
    this.state = {
      ...props.user.body,
      photoPath: props.user.body.avatar,
    };
  }

  openPlacePicker = (updateOnlyLocation = false) => {
    RNGooglePlaces.openPlacePickerModal({
      type: 'establishment',
      country: 'PL',
    })
      .then((place) => RNGooglePlaces.lookUpPlaceByID(place.placeID))
      .then((results) => {
        console.log();
        const { photoUri, phoneNumber, name, address, latitude, longitude, placeID, website } = results;
        this.setState({
          ...this.state,
          businessLocation: {
            address,
            latitude,
            longitude,
            name,
            googleID: placeID,
          },
        });
        if (!updateOnlyLocation) {
          this.setState({
            ...this.state,
            photoPath: photoUri,
            avatar: photoUri,
            googleID: placeID,
            website,
            name,
            phoneNumber,
          });
        }
      })
      .catch((error) => console.log(error.message));
  }

  save = () => {
    const { onSaveBody, onSaveImage, user: { body: { id, avatar } } } = this.props;
    const { photoPath, ...body } = this.state;
    if (photoPath !== avatar) {
      if (!photoPath.startsWith('http')) {
        onSaveImage(id, photoPath);
        onSaveBody(id, body);
      } else {
        onSaveBody(id, { ...body, avatar: photoPath });
      }
    } else {
      onSaveBody(id, body);
    }
  }

  renderSaveButton() {
    const { loading } = this.props;
    return (
      <Button
        buttonStyle={{ padding: 8 }}
        loading={loading}
        title={loading ? '' : 'Zapisz'}
        onPress={this.save}
        activityIndicatorStyle={{ height: 25 }}
      />
    );
  }

  render() {
    const body = this.state;
    return (
      <View>
        <Header
          title='Pracodawca'
          rightComponent={this.renderSaveButton()}
        />
        <KeyboardAwareScrollView extraHeight={50} enableOnAndroid={true} viewIsInsideTabBar={true}>
          <View style={{ flex: 1, paddingBottom: 12 }}>
            <BigButton
              onPress={() => this.openPlacePicker()}
              backgroundColor='#f4a142'
              title={'Znajdź swój biznes w Google'}
              iconRight={{
                name: 'search',
              }}
              containerViewStyle={styles.businessPickerBackground}
              buttonStyle={{ height: 40, padding: 12, borderRadius: 5 }}
            />
            <PhotoArea
              photoUrl={body.avatar}
              onNewPath={(photoPath) => this.setState({ photoPath })}
              editable={true}
            />
            <Card title='Informacje' containerStyle={{ marginHorizontal: -12 }}>
              <FormLabel>Nazwa</FormLabel>
              <FormInput
                value={body.name}
                editable={true}
                onChangeText={(name) => this.setState({ name })}
              />
              <FormLabel>Opis</FormLabel>
              <FormInput
                multiline={true}
                value={body.description}
                editable={!this.props.loading}
                onChangeText={(description) => this.setState({ description })}
              />
              <FormLabel>Strona internetowa</FormLabel>
              <FormInput
                value={body.website}
                editable={true}
                onChangeText={(website) => this.setState({ website })}
              />
              <FormLabel>Telefon</FormLabel>
              <FormInput
                keyboardType={'phone-pad'}
                value={body.phoneNumber}
                editable={true}
                onChangeText={(phoneNumber) => this.setState({ phoneNumber })}
              />
            </Card>
            <LocationInfo
              location={this.state.businessLocation}
              onEditRequest={() => this.openPlacePicker(true)}
            />
          </View>
        </KeyboardAwareScrollView>
      </View>
    );
  }
}

const mapStateToProps: (state: RootState) => StateProps =
  (state) => ({
    user: state.user as Employer,
    loading: state.network.user.update.loading,
    error: state.network.user.update.error,
  });

const mapDispatchToProps: (dispatch: Dispatch<RootState>) => DispatchProps =
  (dispatch) => ({
    onSaveBody: (userId: string, user: EmployerBody) =>
      dispatch(UserActions.userProfileEditRequest(userId, user)),
    onSaveImage: (userId, photoPath: string) =>
      dispatch(UserActions.userPhotoUploadRequested(userId, photoPath)),
    onClose: () => dispatch(NavigationActions.back()),
  });

const styles = StyleSheet.create({
  businessPickerBackground: {
    marginLeft: 0,
    marginRight: 0,
    backgroundColor: Colors.employer.primary,
    padding: 8,
  },
});

export const EmployerProfileEdit = connect(mapStateToProps, mapDispatchToProps)(EmployerProfileEditForm);
