import React, {useEffect, useState, useMemo} from 'react';
import {
  View,
  StyleSheet,
  Dimensions,
  Text,
  TouchableOpacity,
  TextInput,
  FlatList,
  Image,
} from 'react-native';
import {Colors, FONTS} from 'global-styles';
import {RFValue} from 'react-native-responsive-fontsize';
import {Icon} from 'components';
import Modal from 'react-native-modal';
import {useTranslation} from 'react-i18next';
import MapView, {PROVIDER_GOOGLE, Marker} from 'react-native-maps';
const {width, height} = Dimensions.get('window');
import debounce from 'lodash.debounce';
import {searchPlace} from 'services';

const ASPECT_RATIO = width / height;
const LATITUDE_DELTA = 0.001;

const _Maps = props => {
  const {t} = useTranslation();
  const {label, note, error, required} = props;
  const [modal, setModal] = useState(false);
  const [location, setLocation] = useState({
    name: '',
    address: '',
    coordinate: {},
  });
  const [keyword, setKeyword] = useState('');
  const [places, setPlaces] = useState([]);

  useEffect(() => {
    return () => {
      debouncedResults.cancel();
    };
  });

  const handleSearchPlace = async e => {
    setKeyword(e);
    const {_data, _error} = await searchPlace(e);
    if (_error) {
      console.log(_error);
      return;
    }
    setPlaces(_data);
  };

  const debouncedResults = useMemo(() => {
    return debounce(handleSearchPlace, 300);
  }, []);

  return (
    <View style={styles.container}>
      {label && (
        <Text style={styles.label}>
          {label}
          {required && <Text style={{color: Colors.RED}}>*</Text>}
        </Text>
      )}
      <TouchableOpacity
        activeOpacity={0.5}
        onPress={() => setModal(true)}
        style={styles.inputSection}>
        <Icon
          name="map-marker-radius"
          type="MaterialCommunityIcons"
          style={styles.mapIcon}
        />
        <Text style={styles.inputPlaceholder}>Pilih lokasi</Text>
      </TouchableOpacity>
      {note && <Text style={styles.note}>{note}</Text>}
      {error && (
        <View style={styles.errorSection}>
          <Icon name="error" type="MaterialIcons" style={styles.errorIcon} />
          <Text style={styles.errorText}>{error}</Text>
        </View>
      )}

      <Modal isVisible={modal} style={styles.modal}>
        <View style={styles.modalSection}>
          <TouchableOpacity
            onPress={() => setModal(false)}
            style={styles.buttonClose}>
            <Icon
              name="close"
              type="AntDesign"
              style={styles.buttonCloseIcon}
            />
          </TouchableOpacity>
          <View style={styles.content}>
            <View style={styles.header}>
              <Text style={styles.title}>
                {t('select_outlet_location_text')}
              </Text>
              {location.coordinate?.latitude ? (
                <TouchableOpacity
                  onPress={() =>
                    setLocation({name: '', address: '', coordinate: {}})
                  }
                  style={styles.buttonSearch}>
                  <Icon
                    name="search"
                    type="Feather"
                    style={styles.searchIcon}
                  />
                </TouchableOpacity>
              ) : (
                <View style={styles.inputSearchSection}>
                  <TextInput
                    style={styles.input}
                    onChangeText={debouncedResults}
                    placeholder={t('search_placeholder')}
                  />
                  <Icon
                    name="search"
                    type="Feather"
                    style={styles.searchIcon}
                  />
                </View>
              )}
            </View>

            {!location.coordinate?.latitude && (
              <FlatList
                data={places}
                keyExtractor={(item, index) => index.toString()}
                renderItem={({item, index}) => (
                  <View style={styles.locationContainer}>
                    <TouchableOpacity
                      activeOpacity={0.7}
                      onPress={() =>
                        setLocation({
                          name: item.text_id,
                          address: item.place_name_id,
                          coordinate: {
                            latitude: item.geometry.coordinates[1],
                            longitude: item.geometry.coordinates[0],
                            latitudeDelta: LATITUDE_DELTA,
                            longitudeDelta: LATITUDE_DELTA * ASPECT_RATIO,
                          },
                        })
                      }
                      style={styles.locationSection}>
                      <Icon
                        name="my-location"
                        type="MaterialIcons"
                        style={styles.myLoationIcon}
                      />
                      <View style={styles.locationInfoSection(true)}>
                        <Text style={styles.locationInfoName}>
                          {item.text_id}
                        </Text>
                        <Text
                          numberOfLines={2}
                          style={styles.locationInfoAddress}>
                          {`${item.place_name_id}`}
                        </Text>
                      </View>
                    </TouchableOpacity>
                  </View>
                )}
              />
            )}

            {location.coordinate?.latitude && (
              <React.Fragment>
                <View style={styles.mapSection}>
                  <MapView
                    provider={PROVIDER_GOOGLE}
                    style={styles.map}
                    zoomEnabled={true}
                    initialRegion={location.coordinate}
                    onRegionChangeComplete={v =>
                      setLocation({...location, coordinate: v})
                    }>
                    <Marker coordinate={location.coordinate}>
                      <Image
                        source={require('assets/images/marker.png')}
                        style={styles.marker}
                      />
                    </Marker>
                  </MapView>
                </View>
                <View style={styles.buttonSection}>
                  <TouchableOpacity
                    activeOpacity={0.7}
                    disabled
                    style={styles.locationSection}>
                    <Icon
                      name="my-location"
                      type="MaterialIcons"
                      style={styles.myLoationIcon}
                    />
                    <View style={styles.locationInfoSection(false)}>
                      <Text style={styles.locationInfoName}>
                        {location.name}
                      </Text>
                      <Text
                        numberOfLines={2}
                        style={styles.locationInfoAddress}>
                        {location.address}
                      </Text>
                    </View>
                  </TouchableOpacity>
                  <TouchableOpacity
                    onPress={() => alert('saved')}
                    style={styles.button}>
                    <Text style={styles.buttonTitle}>{t('save')}</Text>
                  </TouchableOpacity>
                </View>
              </React.Fragment>
            )}
          </View>
        </View>
      </Modal>
    </View>
  );
};

_Maps.defaultProps = {
  note: undefined,
  error: undefined,
  required: false,
};

const styles = StyleSheet.create({
  container: {},
  label: {
    fontFamily: FONTS.poppins[600],
    fontSize: RFValue(11.5),
    color: Colors.TEXT,
  },
  inputSection: {
    height: width * 0.45,
    borderWidth: 1,
    borderColor: Colors.DISABLED,
    borderRadius: width * 0.02,
    marginVertical: width * 0.023,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: width * 0.04,
    backgroundColor: Colors.DISABLED,
    flexDirection: 'row',
  },
  mapIcon: {
    fontSize: RFValue(18),
    color: Colors.PRIMARY,
  },
  inputPlaceholder: {
    fontFamily: FONTS.poppins[500],
    fontSize: RFValue(11),
    color: Colors.TEXT,
    marginTop: width * 0.003,
    marginLeft: width * 0.01,
  },
  note: {
    fontFamily: FONTS.poppins[400],
    fontSize: RFValue(10),
    color: Colors.TEXT_LIGHT,
    marginTop: -width * 0.005,
  },
  errorSection: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: width * 0.002,
  },
  errorIcon: {
    color: Colors.RED,
  },
  errorText: {
    fontFamily: FONTS.poppins[400],
    fontSize: RFValue(10),
    color: Colors.RED,
    marginTop: -width * 0.001,
    marginLeft: width * 0.01,
  },

  // modal styled
  modal: {
    margin: 0,
  },
  modalSection: {
    flex: 1,
    margin: 0,
    justifyContent: 'flex-end',
  },
  content: {
    height: height / 1.2,
    backgroundColor: Colors.WHITE,
    // paddingVertical: width * 0.04,
    // paddingHorizontal: width * 0.05,
    borderTopLeftRadius: width * 0.05,
    borderTopRightRadius: width * 0.05,
  },
  header: {
    paddingVertical: width * 0.05,
    paddingHorizontal: width * 0.05,
  },
  title: {
    fontFamily: FONTS.poppins[600],
    fontSize: RFValue(13),
    color: Colors.TEXT,
  },
  inputSearchSection: {
    height: width * 0.12,
    borderWidth: 1,
    borderColor: Colors.LINE_STROKE,
    borderRadius: width * 0.02,
    marginVertical: width * 0.023,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: width * 0.04,
    backgroundColor: Colors.DISABLED,
    flexDirection: 'row',
  },
  searchIcon: {
    fontSize: RFValue(20),
    color: Colors.GREY,
  },
  input: {
    flex: 1,
    fontFamily: FONTS.poppins[400],
    fontSize: RFValue(13),
    color: Colors.TEXT,
  },
  locationContainer: {
    paddingHorizontal: width * 0.05,
  },
  locationSection: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    marginBottom: width * 0.03,
  },
  myLoationIcon: {
    fontSize: RFValue(16),
    color: Colors.TEXT,
    marginRight: width * 0.03,
  },
  locationInfoSection: isBordered => ({
    flex: 1,
    borderBottomWidth: isBordered ? 1 : 0,
    borderBottomColor: Colors.LINE_STROKE,
    paddingBottom: width * 0.04,
  }),
  locationInfoName: {
    fontFamily: FONTS.poppins[500],
    fontSize: RFValue(12),
    color: Colors.TEXT,
    marginTop: -width * 0.002,
    marginBottom: width * 0.008,
  },
  locationInfoAddress: {
    fontFamily: FONTS.poppins[400],
    fontSize: RFValue(11),
    color: Colors.TEXT,
  },

  buttonSearch: {
    position: 'absolute',
    right: width * 0.05,
    top: width * 0.046,
  },

  // maps section
  mapSection: {
    // height: width * 1.2,
    height: height,
    width: width,
  },
  map: {
    // flex: 1,
    // height: 500,
    height: height - width * 1,
  },
  buttonClose: {
    backgroundColor: Colors.WHITE,
    width: width * 0.09,
    height: width * 0.09,
    borderRadius: width,
    marginBottom: width * 0.03,
    alignSelf: 'flex-end',
    marginRight: width * 0.03,
    alignItems: 'center',
    justifyContent: 'center',
  },
  buttonCloseIcon: {
    fontSize: RFValue(20),
    color: Colors.TEXT,
  },

  buttonSection: {
    width: width,
    backgroundColor: Colors.WHITE,
    position: 'absolute',
    bottom: 0,
    height: width * 0.5,
    paddingVertical: width * 0.05,
    paddingHorizontal: width * 0.05,
    borderTopLeftRadius: width * 0.04,
    borderTopRightRadius: width * 0.04,
    justifyContent: 'flex-end',
  },
  button: {
    backgroundColor: Colors.PRIMARY,
    height: width * 0.11,
    borderRadius: width * 0.015,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: width * 0.05,
  },
  buttonTitle: {
    fontFamily: FONTS.poppins[500],
    color: Colors.WHITE,
    fontSize: RFValue(12),
    marginTop: width * 0.005,
  },
  marker: {
    width: width * 0.15,
    height: width * 0.15,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,

    elevation: 5,
  },
});

export default _Maps;
