/* eslint-disable react/style-prop-object */
import * as WebBrowser from 'expo-web-browser';
import * as React from 'react';
import { StatusBar } from 'expo-status-bar';
import { Div } from 'react-native-magnus';
import { Appbar } from 'react-native-paper';
import { WebView } from 'react-native-webview';
import { useTranslation } from 'react-i18next';

import { useRoute } from '@react-navigation/native';
import useModel from 'flooks';
import MapModel from './model';

export default function MapScreen({ navigation }) {
  const { t } = useTranslation();
  const { locationInfo, changeChooseInfo } = useModel(MapModel, [
    'locationInfo',
  ]);
  const { location } = locationInfo;
  const webRef = React.useRef();
  const [pageType, setpageType] = React.useState('homeSearch');

  const route = useRoute();

  React.useEffect(() => {
    const { params } = route;
    const { type } = params || {};
    if (type) {
      setpageType('addAddress');
    }
  }, [route]);
  return (
    <>
      <StatusBar backgroundColor="#fff" style="dark" translucent />

      <Appbar.Header
        theme={{ colors: { primary: '#fff' } }}
        style={{
          elevation: 0,
          shadowOffset: {
            width: 0,
            height: 0,
          },
          shadowOpacity: 0,
          zIndex: 2,
        }}
      >
        <Appbar.BackAction onPress={navigation.goBack} />
        <Appbar.Content
          title={t('xuan-ze-shou-huo-di-zhi')}
          titleStyle={{ textAlign: 'center', fontSize: 16 }}
        />
        <Div w={56} h={56} />
      </Appbar.Header>
      <WebView
        ref={webRef}
        source={{
          uri: `http://dingdong.izouma.com/map/chooseLocation`,
        }}
        style={{ flexGrow: 1, width: '100%' }}
        onMessage={({ nativeEvent }) => {
          const info = JSON.parse(nativeEvent.data);
          if (pageType === 'homeSearch') {
            changeChooseInfo({
              addressName: info.poiname,
              location: info.latlng,
            });
            navigation.navigate('Home');
          } else {
            navigation.navigate('EditAddress', {
              locationInfo: info,
            });
          }
        }}
        onLoad={() => {
          webRef.current.injectJavaScript(
            `window.setLocation('${
              location ? `${location.lat},${location.lng}` : ''
            }')`
          );
        }}
      />
    </>
  );
}
