import { FontAwesome } from "@expo/vector-icons";
import ReactNativeZoomableView from '@openspacelabs/react-native-zoomable-view/src/ReactNativeZoomableView';
import React, { useState } from 'react';
import { Alert, Dimensions, GestureResponderEvent, ImageSourcePropType, StatusBar, StyleSheet, View } from 'react-native';
import Picker from 'react-native-picker-select';
import Toast from 'react-native-root-toast';
import { Image, Svg } from 'react-native-svg';
import { Landmark } from '../../../state/external/landmarks';
import { MapStackNavigationProp } from "../MapNavigator";
import { colors, lmTypesIndoor } from "../../../utils/GlobalUtils";
import IndoorFloor from './indoor-floor';
import ArrowButton from './arrow-button';

interface IndoorMapProps {
  navigation: MapStackNavigationProp;
  landmarks: Landmark[];
  promptAddLandmark: (longitude?: number, latitude?: number, floor?: number) => void;
  focusLandmark: (landmark: Landmark) => void;
  applyFilter: (landmarks: Landmark[]) => Landmark[];
}

const landmarkPinSize = 0.05 * Dimensions.get("window").width;

const IndoorMap: React.FC<IndoorMapProps> = ({ landmarks, promptAddLandmark, focusLandmark, applyFilter }) => {
  const [floor, setFloor] = useState(1);
  const [SVGdim, setSVGdim] = useState([1, 1])
  const [localLandmarks, setLocalLandmarks] = useState<Landmark[]>([])

  const renderedLandmarks = applyFilter(landmarks)?.map((item) => {
    if (!lmTypesIndoor[item.landmark_type]) {
      return null
    }
    if (item.floor == floor && SVGdim[0] != 1 && SVGdim[1] != 1) {
      return (
        <Image
          onPress={() => focusLandmark(item)}
          key={item.id}
          x={item.longitude * SVGdim[0]}
          y={item.latitude * SVGdim[1]}
          width={landmarkPinSize}
          height={landmarkPinSize}
          href={lmTypesIndoor[item.landmark_type].image as ImageSourcePropType} />
      )
    }
  })


  function addLandmark(evt: GestureResponderEvent) {
    if (evt != null) {
      Alert.alert("Are you sure you want to add a landmark here?", undefined,
        [{ text: "Cancel" }
          ,
        {
          text: "Confirm", onPress: async () => {
            try {
              await promptAddLandmark((evt.nativeEvent.locationX - landmarkPinSize / 2) / SVGdim[0], (evt.nativeEvent.locationY - landmarkPinSize / 2) / SVGdim[1], floor)
            }
            catch (err) {
              Toast.show("Please ensure finger is not moving when holding down on screen.", { duration: Toast.durations.LONG, })

              // Alert.alert("An error has occured." , "Please ensure thumb is not moving when holding down on screen.")
              // consider toast
            }
          }
        }]
      )
    }
  }

  const childToWeb = (child: any) => {
    const { type, props } = child;
    const name = type && type.displayName;
    const webName = name && name[0].toLowerCase() + name.slice(1);
    const Tag = webName ? webName : type;
    return <Tag {...props}>{toWeb(props.children)}</Tag>;
  };

  const toWeb = (children: any) => React.Children.map(children, childToWeb);
  function changer(num) {
    setFloor(prevState => prevState + num)
  }

  // TODO: wire up promptaddlandmark, applyfilters, and focuslandmark methods passed from MapNavigator
  return (
    <View style={{ height: '100%', width: Dimensions.get("screen").width, backgroundColor:colors.red }}>

      <StatusBar backgroundColor={colors.red} />
      {/* <CustomModal /> */}
      {/* <Text style={{ fontSize: 16, marginBottom: 5 }}>Please select a floor you would like to go to.</Text> */}

      <View style={{ borderColor: "blue", borderWidth: 0, maxHeight: 50, flex: 1, flexDirection: "row", justifyContent: "center", }}>

        {floor == 0 ? <ArrowButton num={0} fontAweIcon={""} /> : <ArrowButton num={-1} fontAweIcon={"chevron-left"} propEvent={() => changer(-1)} />}

        <View style={{flex: 5, height: 53.5, width: 200 }}>
          <Picker
            placeholder={{}}
            value={floor}
            style={{ 
              inputIOSContainer: {width:'70%', justifyContent: 'center', alignSelf: 'center'},
              inputAndroid: {textAlign: 'center', color:"white", },
              inputIOS: { color: 'white', textAlign: 'center', height: '100%', alignSelf: 'center'} ,
              iconContainer: {height: '100%', justifyContent: 'center',}
            }}
            onValueChange={(value) => {
              setFloor(value)
            }
            }
            items={[
              { label: 'Basement', value: 0 },
              { label: 'First Floor', value: 1 },
              { label: 'Second Floor', value: 2 },
              { label: 'Third Floor', value: 3 },
              { label: 'Fourth Floor', value: 4 },
              { label: 'Fifth Floor', value: 5 },
            ]}
          />
        </View>


        {/* {floor == 5 ? arrowBut(0, "") : arrowBut(1, "chevron-right")} */}
        {floor == 5 ? <ArrowButton num={0} fontAweIcon={""} /> : <ArrowButton num={1} fontAweIcon={"chevron-right"} propEvent={() => changer(1)} />}


      </View>

      <View style={{ flex: 1, alignItems: "center", height: '100%', width: '100%', borderColor: 'purple', borderWidth: 0 }}>
        <View style={styles.container}>
          {/* {showME === false ?
            <View style={{ display: 'flex', flexDirection: 'row', justifyContent: "center", }}>
              <ActivityIndicator color={colors.red} size="large" />
            </View> : */}

            <ReactNativeZoomableView
              panBoundaryPadding={100}
              bindToBorders={true}
              zoomStep={2.8}
              maxZoom={5}
              minZoom={1}
              initialOffsetY={5}
              onLongPress={(event) => addLandmark(event)}
              movementSensibility={2}
              longPressDuration={200}
              >

              <Svg onLayout={event => {
                setSVGdim([event.nativeEvent.layout.width, event.nativeEvent.layout.height])
                const transformedLandmarks = localLandmarks.map(item => {
                  return { ...item, coordx: item.longitude * event.nativeEvent.layout.width, coordy: item.latitude * event.nativeEvent.layout.height }
                })
                //console.log("*this is within onLayout* SVGdim values are " + SVGdim[0] + " AND " + SVGdim[1])
                setLocalLandmarks(transformedLandmarks)
              }}
              >
                {/* {firstTime == true ? undefined : loadCircles} */}
                <IndoorFloor floorNum={floor} />
                {renderedLandmarks}
              </Svg>
            </ReactNativeZoomableView>
          {/* } */}

        </View>
      </View>
    </View >
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    // backgroundColor: "#fff",
    justifyContent: "center",
    borderColor: "black",
    borderWidth: 0,
    marginVertical: 0,
    aspectRatio: 8 / 10,  // (caters to portrait mode) (width is 80% the value of height dimension)
    width: '100%',
    height: '100%',
    maxWidth: "100%",
    maxHeight: "100%",
    backgroundColor:"white",
    
  },
  image: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  png: {
    borderColor: "red",
    borderWidth: 3
  },
  arrowButton: {
    flex: 1,
    backgroundColor: colors.red,
    height: 53.5,
  },
});


export default IndoorMap;