import React, { useState, useEffect, Children } from 'react';
import { View, Text, StatusBar, StyleSheet, Dimensions, Button, ActivityIndicator, Alert, Modal, PanResponderCallbacks, PanResponderGestureState, GestureResponderEvent, ImageSourcePropType, TouchableOpacity, Platform } from 'react-native';
import { Svg, Defs, Rect, Mask, Circle, Marker, Path, Polyline, Image } from 'react-native-svg';
import { RadioButton } from 'react-native-paper';
import { Picker } from '@react-native-picker/picker';
import ReactNativeZoomableView from '@openspacelabs/react-native-zoomable-view/src/ReactNativeZoomableView';
import Spinner from 'react-native-spinkit'
import { colors, lmTypes } from "../../../utils/GlobalUtils";
import { MapStackNavigationProp } from "../../../navigation/MapNavigator"
import CustomModal from './modal';
import { FontAwesome } from "@expo/vector-icons";
import ReactDOMServer from 'react-dom/server'; //npm i --save-dev @types/react-dom


import BasementC from './images/BasementC.svg';
import FirstFloorC from './images/FirstFloorC.svg'
import SecondFloorC from './images/SecondFloorC.svg'
import ThirdFloorC from './images/ThirdFloorC.svg'
import FourthFloorC from './images/FourthFloorC.svg'
import FifthFloorC from './images/FifthFloorC.svg'
import { ZoomableViewEvent } from '@openspacelabs/react-native-zoomable-view/src/typings';
import { Landmark } from '../../../data/landmarks';


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




const IndoorMap: React.FC<IndoorMapProps> = ({ navigation, landmarks, promptAddLandmark, focusLandmark, applyFilter }) => {
  const [floor, setFloor] = useState(0);
  const [showME, setShowME] = useState(false);
  const [showDots, setShowDots] = useState(false);
  const [showAddedDot, setShowAddedDot] = useState(false)
  const [SVGdim, setSVGdim] = useState([1, 1])

  const [localLandmarks, setLocalLandmarks] = useState<Landmark[]>([])

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

  function arrowBut(num, fontAweIcon) {
    if (num != 0) {
      return (
        <View style={{ flex: 1.2, marginHorizontal: 7, backgroundColor: "#d4d4d4", height: 53.5, maxWidth: 60 }}>
          <TouchableOpacity style={styles.arrowButton} onPress={() => { setFloor(prevState => prevState + num) }}>
            <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
              {/* <FontAwesomeIcon icon="fa-solid fa-left" /> */}
              <FontAwesome style={{ marginLeft: (num == 1 ? 5 : -5) }} color={"white"} size={35} name={fontAweIcon} />
            </View>
          </TouchableOpacity>
        </View>
      )
    }
    else {
      return (
        <View style={{ flex: 1.2, marginHorizontal: 7, height: 53.5, maxWidth: 60, borderRadius: 10 }}>
        </View>
      )
    }
  }


  const loadCircles = applyFilter(landmarks)?.map((item) => {
    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={imageDim}
          height={imageDim}
          href={lmTypes[item.landmark_type]['image'] as ImageSourcePropType} />
      )
    }
  }
  )


  function addLandmark(evt: GestureResponderEvent) {
    if (evt) {
      Alert.alert("Are you sure you want to add a landmark here?", undefined,
        [{ text: "Cancel" }
          ,
        {
          text: "Confirm", onPress: async () => {
            await promptAddLandmark((evt.nativeEvent.locationX - imageDim / 2) / SVGdim[0], (evt.nativeEvent.locationY - imageDim / 2) / SVGdim[1], floor)
          }
        }])
    }
  }



  useEffect(() => {
    // Alert.alert("useEffect has been triggered")
    setShowAddedDot(false)
    setShowDots(false)
    setTimeout(() => setShowME(true), 100);
  })



  const compArray = [
    <BasementC style={{ opacity: 0.7 }} height={"100%"} width={"100%"} />,
    <FirstFloorC style={{ opacity: 0.7 }} height={"100%"} width={"100%"} />,
    <SecondFloorC style={{ opacity: 0.7 }} height={"100%"} width={"100%"} />,
    <ThirdFloorC viewBox='250 136 310 310' style={{ opacity: 0.7 }} height={"100%"} width={"100%"} />,
    <FourthFloorC viewBox='260 151 270 260' style={{ opacity: 0.7 }} height={"100%"} width={"100%"} />,
    <FifthFloorC viewBox='257 153 270 290' style={{ opacity: 0.7 }} height={"100%"} width={"100%"} />,
  ]


  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 renderSvg() {
    return (
      <Svg height="100%" width="100%" style={{ backgroundColor: '#33AAFF' }}>
      <Rect
        x="50"
        y="50"
        width="50"
        height="50"
        fill="#3399ff"
        strokeWidth="3"
        stroke="rgb(0,0,0)"
      />
    </Svg>
    )
  }

  function serialize() {
    const element = renderSvg();
    const webJsx = Platform.OS === 'web' ? element : toWeb(element);
    const svgString = ReactDOMServer.renderToStaticMarkup(webJsx);
    //console.log(svgString)
    // setText(svgString)
    return svgString
  }




  // TODO: wire up promptaddlandmark, applyfilters, and focuslandmark methods passed from MapNavigator
  return (
    <View style={{ height: '100%', width: '100%', padding: 5 }}>
      {/* {console.log("THE STATE IS NOW " + floor)} */}

      <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", }}>

        {/* arrow-circle-o-right */}
        {floor == 0 ? arrowBut(0, "") : arrowBut(-1, "chevron-left")}


        <Picker
          style={{ backgroundColor: colors.red, width: 200, height: 50, flex: 5, color: 'white' }}
          selectedValue={floor} // the text of what gets displayed on the dropdown header
          onValueChange={(itemValue, itemIndex: number) => {
            setFloor(itemIndex)
            setShowME(false)
          }}>
          {/* The value in Picker.Item refers to selectedValue in Picker, which refers to the state "floor" */}
          <Picker.Item label="Basement" value={0} />
          <Picker.Item label="First Floor" value={1} />
          <Picker.Item label="Second Floor" value={2} />
          <Picker.Item label="Third Floor" value={3} />
          <Picker.Item label="Fourth Floor" value={4} />
          <Picker.Item label="Fifth Floor" value={5} />
        </Picker>

        {floor == 5 ? arrowBut(0, "") : arrowBut(1, "chevron-right")}

      </View>



      <View style={{ flex: 1, alignItems: "center", height: '100%', width: '100%' }}>
        <View style={styles.container}>
          {showME === false ?
            <View style={{ display: 'flex', flexDirection: 'row', justifyContent: "center", }}>
              <Spinner size={200} color={colors.red} type="9CubeGrid" />
            </View> :

            <ReactNativeZoomableView
              panBoundaryPadding={100}
              // bindToBorders={false}
              bindToBorders={true}


              zoomStep={2.8}
              // initialZoom={2.2}
              maxZoom={2.8}
              minZoom={1}
              initialOffsetY={5}
              onLongPress={(event) => {
                //console.log(event.nativeEvent)
                serialize()
                addLandmark(event)
              }}>



              <Svg onLayout={event => {
                // console.log("OFFICIAL: " + event.nativeEvent.layout.width + " , " + event.nativeEvent.layout.height)
                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} */}
                {loadCircles}
                {compArray[floor]}
              </Svg>





            </ReactNativeZoomableView>

          }

        </View>
      </View>
      {/* <Button title="load coordinates" onPress={() => {
        setfirstTime(false)
        setLocalLandmarks(landmarks)
      }} /> */}

      <Button title='Press me to svgString' color={colors.red} onPress={serialize}></Button>
      {/* <Button title="Go back to map" color={colors.red} onPress={() => navigation.goBack()} /> */}
      {/* <TouchableOpacity style={styles.arrowButton} onPress={() => setFloor(prevState => prevState+1)} ><Text>Increase floor by 1</Text></TouchableOpacity> */}

    </View>
  );
}

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

  }
});


export default IndoorMap;