import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  FlatList,
  Keyboard,
} from "react-native";
import React, { useCallback, useRef, useState, useEffect } from "react";
import { Button, HeaderContainer } from "@src/commonComponent";
import { appColors, windowHeight, windowWidth } from "@src/themes";
import { Gps, History, PickLocation } from "@src/utils/icons";
import { styles } from "./styles";
import { useNavigation, useRoute } from "@react-navigation/native";
import { getValue, setValue } from "@src/utils/localstorage";
import { useDispatch, useSelector } from "react-redux";
import { ambulanceAction } from "@src/api/store/actions";
import { useValues } from "@src/utils/context/index";
import useStoredLocation from "@src/components/helper/useStoredLocation";
import { AppDispatch } from "@src/api/store";
import { external } from "@src/styles/externalStyle";

export function AmbulanceLocation() {
  const [pickup, setPickup] = useState<string>("");
  const [suggestions, setSuggestions] = useState<any>([]);
  const [isPickupField, setIsPickupField] = useState<boolean>(true);
  const inputTimer = useRef<any>(null);
  const [recentAddresses, setRecentAddresses] = useState<string[]>([]);
  const [pickupCoords, setPickupCoords] = useState<any>(null);
  const [isLoadingCoords, setIsLoadingCoords] = useState<boolean>(true);
  const navigation = useNavigation<any>();
  const webViewRef = useRef<any>(null);
  const dispatch = useDispatch<AppDispatch>();
  const { textColorStyle, viewRTLStyle, textRTLStyle, isDark, Google_Map_Key } =
    useValues();
  const { translateData } = useSelector((state: any) => state.setting);
  const { latitude, longitude } = useStoredLocation();
  const route = useRoute<any>();
  const { currentAddress, isAmbulanceLocation } = route.params || {};
  const [finalAddress, setFinalAddress] = useState<string>("");

  useEffect(() => {
    loadRecentAddresses();
    if (latitude && longitude) fetchAddressFromCoords(latitude, longitude);
  }, [latitude, longitude]);

  useEffect(() => {
    if (currentAddress) {
      setPickup(currentAddress);
      setFinalAddress(currentAddress);
    }
  }, [currentAddress]);

  const loadRecentAddresses = async () => {
    const savedAddresses = await getValue("ambulanceLocations");
    if (savedAddresses) setRecentAddresses(JSON.parse(savedAddresses));
  };

  const fetchAddressFromCoords = async (latitude: any, longitude: any) => {
    if (!latitude || !longitude) {
      setIsLoadingCoords(false);
      return;
    }
    setIsLoadingCoords(true);
    const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${Google_Map_Key}&result_type=street_address`;
    try {
      const response = await fetch(url);
      const json = await response.json();
      if (json.status === "OK" && json.results.length > 0) {
        const address = json.results[0].formatted_address;
        setPickup(address);
        setFinalAddress(address);
        const coords: any = { latitude, longitude };
        setPickupCoords(coords);
        updateWebViewMap(coords);
      }
    } catch (error) {
    } finally {
      setIsLoadingCoords(false);
    }
  };

  const fetchCoordinates = async (
    address: string | number | boolean,
    isPickup: any
  ) => {
    const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(
      address
    )}&key=${Google_Map_Key}`;
    try {
      const response = await fetch(url);
      const json = await response.json();
      if (json.status === "OK" && json.results.length > 0) {
        const location = json.results[0].geometry.location;
        const coords = { latitude: location.lat, longitude: location.lng };
        if (isPickup) {
          setPickupCoords(coords);
          updateWebViewMap(coords);
        }
      }
    } catch (error) {}
  };

  const updateWebViewMap = (coords: any) => {
    if (webViewRef.current && coords) {
      const script = `
        if (window.map && window.marker) {
          window.marker.setPosition({lat: ${coords.latitude}, lng: ${coords.longitude}});
          window.map.setCenter({lat: ${coords.latitude}, lng: ${coords.longitude}});
          window.map.setZoom(15);
        }
      `;
      webViewRef.current.postMessage(script);
    }
  };

  const handleSelectSuggestion = async (address: any, isPickup: any) => {
    setPickup(address);
    setFinalAddress(address);
    if (isPickup) fetchCoordinates(address, true);
    else fetchCoordinates(address, false);
    setSuggestions([]);
    Keyboard.dismiss();
  };

  const fetchAddressSuggestions = useCallback(async (text: string) => {
    if (text.length < 3) {
      setSuggestions([]);
      return;
    }
    const url = `https://maps.googleapis.com/maps/api/place/autocomplete/json?input=${text}&key=${Google_Map_Key}&types=geocode`;
    try {
      const response = await fetch(url);
      const json = await response.json();
      if (json.status === "OK" && json.predictions.length > 0) {
        setSuggestions(json.predictions.slice(0, 2));
      } else {
        setSuggestions([]);
      }
    } catch (error) {}
  }, []);

  const handleInputChange = (text: string, isPickup: any) => {
    setPickup(text);
    setFinalAddress(text);
    setIsPickupField(isPickup);
    if (inputTimer.current) clearTimeout(inputTimer.current);
    inputTimer.current = setTimeout(() => {
      fetchAddressSuggestions(text);
    }, 500);
  };

  const gotoBookAmbulance = async () => {
    try {
      const locationData = { 0: finalAddress };
      await setValue("ambulanceLocations", JSON.stringify(locationData));
      const response = await fetch(
        `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(
          finalAddress
        )}&key=${Google_Map_Key}`
      );
      const dataMap = await response.json();
      if (dataMap.results.length > 0) {
        const location = dataMap.results[0].geometry.location;
        dispatch(ambulanceAction({ lat: location.lat, lng: location.lng }));
        navigation.navigate("BookAmbulance", {
          location: finalAddress,
          lat: location.lat,
          lng: location.lng,
        });
      }
    } catch (error) {}
  };

  const gotoSelection = () => {
    navigation.navigate("LocationSelect", { isAmbulanceLocation: true });
  };

  return (
    <View
      style={[
        styles.container,
        {
          backgroundColor: isDark ? appColors.solidBorder : appColors.lightGray,
        },
      ]}
    >
      <HeaderContainer value={translateData.location} />
      <View
        style={[
          styles.inputContainer,
          {
            backgroundColor: isDark
              ? appColors.solidBorder
              : appColors.lightGray,
          },
        ]}
      >
        <View
          style={{
            backgroundColor: isDark
              ? appColors.primaryText
              : appColors.whiteColor,
            marginTop: windowHeight(15),
            marginHorizontal: windowWidth(18),
            borderWidth: windowWidth(0.45),
            borderColor: isDark ? appColors.darkBorder : appColors.go,
            borderRadius: windowWidth(15),
          }}
        >
          <View style={{ paddingHorizontal: windowWidth(5) }}>
            <View
              style={[
                styles.inputBox,
                {
                  flexDirection: viewRTLStyle,
                  backgroundColor: isDark
                    ? appColors.primaryText
                    : appColors.whiteColor,
                },
              ]}
            >
              <View
                style={[
                  styles.iconContainer,
                  {
                    backgroundColor: isDark
                      ? appColors.solidBorder
                      : appColors.lightGray,
                  },
                ]}
              >
                <PickLocation />
              </View>
              <TextInput
                placeholderTextColor={
                  isDark ? appColors.whiteColor : appColors.blackColor
                }
                placeholder={translateData.pickupLocation}
                style={[
                  styles.input,
                  {
                    textAlign: textRTLStyle,
                    color: isDark ? appColors.darkText : appColors.blackColor,
                  },
                ]}
                value={pickup}
                onChangeText={(text) => handleInputChange(text, true)}
              />
            </View>
          </View>
          <View
            style={[
              styles.line,
              {
                backgroundColor: isDark
                  ? appColors.solidBorder
                  : appColors.lightGray,
              },
            ]}
          />
          <TouchableOpacity
            activeOpacity={0.7}
            style={[
              styles.pickBtn,
              { flexDirection: viewRTLStyle },
              {
                backgroundColor: isDark
                  ? appColors.solidBorder
                  : appColors.lightGray,
              },
            ]}
            onPress={gotoSelection}
          >
            <View style={external.mh_5}>
              <Gps colors={isDark ? appColors.whiteColor : appColors.gray} />
            </View>
            <Text style={[styles.locationText, { color: textColorStyle }]}>
              {translateData.locateonmap}
            </Text>
          </TouchableOpacity>
        </View>
      </View>
      <View>
        <Text
          style={[
            styles.suggestionText,
            {
              textAlign: textRTLStyle,
              color: isDark ? appColors.whiteColor : appColors.blackColor,
            },
          ]}
        >
          {suggestions.length > 0
            ? translateData.suggestedAddresses
            : translateData.recentAddresses}
        </Text>
        <View
          style={{
            backgroundColor: isDark
              ? appColors.primaryText
              : appColors.whiteColor,
            marginHorizontal: windowWidth(15),
            marginTop: windowHeight(15),
            borderWidth: windowWidth(0.45),
            borderColor: isDark ? appColors.darkBorder : appColors.go,
            borderRadius: windowWidth(15),
            paddingBottom: windowHeight(8),
            paddingTop: windowHeight(5),
          }}
        >
          <View>
            <FlatList
              data={suggestions.length > 0 ? suggestions : []}
              keyExtractor={(item, index) =>
                item?.address || item?.place_id || index.toString()
              }
              renderItem={({ item, index }) => {
                const isLastItem = index === suggestions.length - 1;
                return (
                  <View>
                    <TouchableOpacity
                      activeOpacity={0.7}
                      onPress={() =>
                        handleSelectSuggestion(
                          item?.address || item?.description,
                          isPickupField
                        )
                      }
                      style={[
                        styles.suggestionItem,
                        { flexDirection: viewRTLStyle },
                      ]}
                    >
                      <View
                        style={[
                          styles.round,
                          {
                            backgroundColor: isDark
                              ? appColors.solidBorder
                              : appColors.lightGray,
                          },
                        ]}
                      >
                        <History />
                      </View>
                      <Text
                        style={[
                          styles.suggestionText1,
                          {
                            color: isDark
                              ? appColors.whiteColor
                              : appColors.blackColor,
                          },
                        ]}
                      >
                        {item?.address || item?.description}
                      </Text>
                    </TouchableOpacity>
                    {!isLastItem && <View style={styles.line} />}
                  </View>
                );
              }}
            />
          </View>

          {suggestions.length > 0 &&
            Object.values(recentAddresses || {}).length > 0 && (
              <View style={styles.line} />
            )}

          <View>
            <FlatList
              data={recentAddresses ? Object.values(recentAddresses) : []}
              keyExtractor={(item, index) => index.toString()}
              renderItem={({ item, index }: any) => {
                const data = Object.values(recentAddresses || {});
                const isLastItem = index === data.length - 1;
                return (
                  <View>
                    <TouchableOpacity
                      activeOpacity={0.7}
                      onPress={() =>
                        handleSelectSuggestion(
                          item?.address || item?.description || item,
                          isPickupField
                        )
                      }
                      style={[
                        styles.suggestionItem,
                        { flexDirection: viewRTLStyle },
                      ]}
                    >
                      <View
                        style={[
                          styles.round,
                          {
                            backgroundColor: isDark
                              ? appColors.solidBorder
                              : appColors.lightGray,
                          },
                        ]}
                      >
                        <History />
                      </View>
                      <Text
                        style={[
                          styles.suggestionText1,
                          {
                            color: isDark
                              ? appColors.whiteColor
                              : appColors.blackColor,
                          },
                        ]}
                      >
                        {item?.address || item?.description || item}
                      </Text>
                    </TouchableOpacity>
                    {!isLastItem && (
                      <>
                        <View style={styles.line} />
                        <View style={styles.line} />
                      </>
                    )}
                  </View>
                );
              }}
            />
          </View>
        </View>
      </View>
      <View style={styles.buttonView}>
        <View style={styles.buttonHz_Space}>
          <Button
            title={translateData.confirmLocation}
            onPress={gotoBookAmbulance}
          />
        </View>
      </View>
    </View>
  );
}
