import React, { useEffect, useState } from "react";
import { View, Text, StyleSheet, PermissionsAndroid, Platform, ActivityIndicator, TouchableOpacity } from "react-native";
import Geolocation from "react-native-geolocation-service";
import { useNavigation } from "@react-navigation/native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { OLA_MAP_KEY } from "../../constants/constants"; // 🔑 your Ola Maps key
import { getLocationWithFallback, requestLocationPermission } from "../../controller/functions";

const NavigationRouteScreen = (props) => {
  const navigation = useNavigation();
  // Initialize storeData from route params
  const params = props.route.params || {};
  const [storeData] = useState(params.storeData || {});
  const [routeData, setRouteData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [statusMessage, setStatusMessage] = useState("Fetching location...");
  // ✅ Fetch cached route data
  const getCachedRoute = async (key) => {
    try {
      const cached = await AsyncStorage.getItem(key);
      if (cached) {
        console.log("Using cached route data");
        return JSON.parse(cached);
      }
      return null;
    } catch (err) {
      console.warn("Error reading cache:", err);
      return null;
    }
  };

  // ✅ Save route data to cache
  const cacheRoute = async (key, data) => {
    try {
      await AsyncStorage.setItem(key, JSON.stringify(data));
      console.log("Route data cached");
    } catch (err) {
      console.warn("Error caching route:", err);
    }
  };

  // ✅ Fetch current location + route with retry and timeout
  const fetchRoute = async (retryCount = 0, maxRetries = 2) => {
    setLoading(true);
    setStatusMessage("Fetching location...");
    try {
      const hasPermission = await requestLocationPermission();
      if (!hasPermission) {
        setError("Location permission denied");
        setLoading(false);
        return;
      }
      // Timeout for geolocation and API
      const timeoutPromise = new Promise((_, reject) => {
        setTimeout(() => reject(new Error("Operation timed out")), 20000); // 20 seconds timeout
      });
      // 📍 Get current location
      let getLocation = await getLocationWithFallback();
    
      const { latitude, longitude } = await Promise.race([getLocation, timeoutPromise]);
      setStatusMessage("Fetching route from server...");
      // Destination coordinates from storeData
      const destinationLat = parseFloat(storeData.Latitude) || 28.5620719;
      const destinationLng = parseFloat(storeData.Longitude) || 77.4449157;
      // Check cache
      const cacheKey = `route_${latitude}_${longitude}_${destinationLat}_${destinationLng}`;
      const cachedRoute = await getCachedRoute(cacheKey);
      if (cachedRoute) {
        setRouteData(cachedRoute);
        navigation.replace("NavigationScreen", { routeData: cachedRoute }); // navigate safely
        setLoading(false);
        return;
      }

      // 🌐 Ola Maps API Call
      //const url = `https://api.olamaps.io/routing/v1/directions?origin=${latitude},${longitude}&destination=${destinationLat},${destinationLng}&mode=driving&api_key=${OLA_MAP_KEY}`;

      const url = `https://api.olamaps.io/routing/v1/routeOptimizer?locations=${latitude},${longitude}|${destinationLat},${destinationLng}&mode=driving&api_key=${OLA_MAP_KEY}`;
      console.log("url", url)
      const fetchRouteData = async () => {
        const response = await fetch(url, {
          method: "POST",
          redirect: "follow",
          // headers: {
          //   // "X-Request-Id": Date.now().toString(),
          //   "Content-Type": "application/json",
          // },
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        return await response.json();
      };

      const data = await Promise.race([fetchRouteData(), timeoutPromise]);
      // Cache the route data
      await cacheRoute(cacheKey, data);
      setRouteData(data);
      navigation.replace("NavigationScreen", { routeData: data }); // navigate safely
      setLoading(false);
    } catch (err) {
      console.error("❌ Error fetching route:", err);
      if (retryCount < maxRetries && err.message !== "Location permission denied") {
        console.log(`Retrying... Attempt ${retryCount + 1}/${maxRetries}`);
        setTimeout(() => fetchRoute(retryCount + 1), 2000);
      } else {
        setError(err.message || "Unable to fetch route");
        setLoading(false);
      }
    }
  };

  // ✅ Trigger route fetch on mount
  useEffect(() => {
    fetchRoute();
    return () => {
      Geolocation.stopObserving();
    };
  }, []);

  return (
    <View style={styles.container}>
      {loading && (
        <View style={styles.statusBox}>
          <ActivityIndicator size="large" color="#1976D2" />
          <Text style={styles.statusText}>{statusMessage}</Text>

        </View>
      )}

      {error && (
        <View style={[styles.statusBox, styles.errorBox]}>
          <Text style={styles.errorText}>{error}</Text>
          <TouchableOpacity
            style={styles.retryButton}
            onPress={() => {
              setError(null);
              setLoading(true);
              fetchRoute();
            }}
          >
            <Text style={styles.retryButtonText}>Try Again</Text>
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#F5F7FA",
    justifyContent: "center",
    alignItems: "center",
    padding: 16,
  },
  statusBox: {
    padding: 20,
    borderRadius: 12,
    backgroundColor: "#E3F2FD",
    alignItems: "center",
  },
  statusText: {
    marginTop: 10,
    fontSize: 16,
    color: "#1976D2",
    fontWeight: "500",
    textAlign: "center",
  },
  errorBox: {
    backgroundColor: "#FFEBEE",
  },
  errorText: {
    fontSize: 16,
    color: "#D32F2F",
    fontWeight: "600",
    textAlign: "center",
  },
  retryButton: {
    marginTop: 10,
    backgroundColor: "#1976D2",
    paddingVertical: 8,
    paddingHorizontal: 16,
    borderRadius: 8,
  },
  retryButtonText: {
    color: "#fff",
    fontSize: 14,
    fontWeight: "600",
  },
});

export default NavigationRouteScreen;
