import {
  View,
  Text,
  Image,
  TouchableOpacity,
} from "react-native";
import React, { useCallback, useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { useValues } from "@src/utils/context/index";
import styles from "./styles";
import {
  useFocusEffect,
  useNavigation,
  useIsFocused,
} from "@react-navigation/native";
import { ArrowDown, Notification } from "@src/utils/icons";
import { appColors, windowHeight } from "@src/themes";
import { getValue } from "@src/utils/localstorage";
import useSmartLocation from "@src/components/helper/locationHelper";

export function ProfileContainer() {
  const navigation = useNavigation<any>();
  const { viewRTLStyle, Google_Map_Key, isRTL, isDark } = useValues();
  const { self } = useSelector((state: any) => state.account);
  const { taxidoSettingData, translateData } = useSelector(
    (state: any) => state.setting
  );
  const { currentLatitude: latitude, currentLongitude: longitude } =
    useSmartLocation();

  const char = self?.name ? self.name.charAt(0) : "";
  const [city, setCity] = useState<string>("");
  const [fullAddress, setFullAddress] = useState<string>("");

  const isFocused = useIsFocused();

  useEffect(() => {
    const getAddress = async () => {
      let lat = await getValue("user_latitude_Selected");
      let lng = await getValue("user_longitude_Selected");

      let finalLat = lat ? parseFloat(lat) : latitude;
      let finalLng = lng ? parseFloat(lng) : longitude;

      if (!finalLat || !finalLng || !Google_Map_Key) {
        setCity("Select Location");
        setFullAddress("Location not selected");
        return;
      }

      try {
        const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${finalLat},${finalLng}&key=${Google_Map_Key}&result_type=street_address`;
        const response = await fetch(url);
        const data = await response.json();

        if (data.status === "OK") {
          const components = data.results[0].address_components;

          const foundCity = components.find(
            (c: any) =>
              c.types.includes("locality") ||
              c.types.includes("administrative_area_level_2")
          )?.long_name;

          const fullAddr = data.results[0]?.formatted_address;

          setCity(foundCity || "City not found");
          setFullAddress(fullAddr || "Address not found");
        } else {
          setCity("City not found");
          setFullAddress("Address not found");
        }
      } catch {
        setCity("City error");
        setFullAddress("Address error");
      }
    };

    getAddress();
  }, [latitude, longitude, taxidoSettingData, Google_Map_Key, isFocused]);

  const handleImagePress = async () => {
    const token = await getValue("token");
    if (token) {
      navigation.navigate("EditProfile");
    }
  };

  const handelNavigation = async () => {
    const token = await getValue("token");
    if (token) {
      navigation.navigate("Notifications");
    } else {
      navigation.navigate("SignIn");
    }
  };

  const gotoLocation = () => {
    navigation.navigate("LocationSelect", { screenValue: "HomeScreen" });
  };

  return (
    <View style={[styles.mainView, { flexDirection: viewRTLStyle }]}>
      <TouchableOpacity onPress={gotoLocation} style={styles.viewText}>
        <Text
          style={[
            styles.selfName,
            {
              textAlign: isRTL ? "right" : "left",
              color: isDark ? appColors.whiteColor : appColors.blackColor,
            },
          ]}
        >
          {city?.split(" ")[0] || translateData?.fecthing}{" "}
          <ArrowDown
            color={isDark ? appColors.whiteColor : appColors.blackColor}
          />
        </Text>

        <View
          style={{
            flexDirection: "row",
            alignItems: "center",
            marginTop: windowHeight(4),
          }}
        >
          <Text
            style={[
              styles.text,
              { color: isDark ? appColors.darkText : appColors.blackColor },
            ]}
          >
            {fullAddress.length > 32
              ? `${fullAddress.substring(0, 32)}...`
              : fullAddress}
          </Text>
        </View>
      </TouchableOpacity>

      <View
        style={[
          styles.box,
          {
            backgroundColor: isDark
              ? appColors.darkHeader
              : appColors.lightGray,
            flexDirection: viewRTLStyle,
          },
        ]}
      >
        <TouchableOpacity
          style={styles.round}
          activeOpacity={0.7}
          onPress={handelNavigation}
        >
          <Notification
            colors={isDark ? appColors.whiteColor : appColors.blackColor}
          />
        </TouchableOpacity>

        <View
          style={[
            styles.divider,
            {
              backgroundColor: appColors.iconColor,
            },
          ]}
        />

        <TouchableOpacity
          onPress={handleImagePress}
          style={styles.imageView}
          activeOpacity={0.7}
        >
          {self?.profile_image_url ? (
            <Image
              style={styles.imageStyle}
              source={{ uri: self.profile_image_url }}
            />
          ) : (
            <View
              style={[
                styles.textView,
                {
                  backgroundColor: isDark
                    ? appColors.whiteColor
                    : appColors.blackColor,
                },
              ]}
            >
              <Text
                style={[
                  styles.charText,
                  {
                    color: isDark
                      ? appColors.blackColor
                      : appColors.whiteColor,
                  },
                ]}
              >
                {char || "G"}
              </Text>
            </View>
          )}
        </TouchableOpacity>
      </View>
    </View>
  );
}
