import { MaterialCommunityIcons } from "@expo/vector-icons";
import { router } from "expo-router";
import { useEffect, useState } from "react";
import { ScrollView, Text, TouchableOpacity, View } from "react-native";

import { POI_CATEGORIES, searchNearby } from "@/lib/places";
import { useLocationStore } from "@/store";
import type { NearbyPlace } from "@/types/type";

// Four quick destination chips: nearest mall / hospital / pharmacy / restaurant
// around the rider. Tapping one sets it as the destination and opens find-ride.
// Each chip resolves independently, so a category with no result nearby just
// shows "none nearby" instead of breaking the whole row.
type ChipState =
  | { status: "loading" }
  | { status: "empty" }
  | { status: "ready"; place: NearbyPlace };

export const NearbySuggestions = () => {
  const { userLatitude, userLongitude, setDestinationLocation } =
    useLocationStore();
  const [chips, setChips] = useState<Record<string, ChipState>>({});

  useEffect(() => {
    if (userLatitude == null || userLongitude == null) return;

    let cancelled = false;
    setChips({});

    // Resolve all four categories in parallel.
    POI_CATEGORIES.forEach(async (category) => {
      setChips((prev) => ({ ...prev, [category.id]: { status: "loading" } }));
      const place = await searchNearby(category.googleType, {
        latitude: userLatitude,
        longitude: userLongitude,
      });
      if (cancelled) return;
      setChips((prev) => ({
        ...prev,
        [category.id]: place ? { status: "ready", place } : { status: "empty" },
      }));
    });

    return () => {
      cancelled = true;
    };
  }, [userLatitude, userLongitude]);

  const select = (place: NearbyPlace) => {
    setDestinationLocation({
      latitude: place.latitude,
      longitude: place.longitude,
      address: place.name,
    });
    router.push("/(root)/find-ride");
  };

  return (
    <View>
      <Text className="text-base font-JakartaSemiBold mb-3">
        Nearby suggestions
      </Text>

      <ScrollView
        horizontal
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={{ gap: 10, paddingBottom: 4 }}
      >
        {POI_CATEGORIES.map((category) => {
          const state = chips[category.id];
          const ready = state?.status === "ready" ? state.place : null;

          return (
            <TouchableOpacity
              key={category.id}
              disabled={!ready}
              onPress={() => ready && select(ready)}
              activeOpacity={0.8}
              className={`flex-row items-center rounded-2xl border px-3 py-2.5 ${
                ready
                  ? "border-primary-500 bg-primary-500/10"
                  : "border-neutral-200 bg-neutral-100"
              }`}
              style={{ minWidth: 150 }}
            >
              <MaterialCommunityIcons
                name={category.icon as never}
                size={20}
                color={ready ? "#0286ff" : "#a3a3a3"}
              />

              <View className="ml-2 flex-1">
                <Text
                  className={`text-xs font-JakartaBold ${
                    ready ? "text-primary-500" : "text-neutral-400"
                  }`}
                  numberOfLines={1}
                >
                  {category.label}
                </Text>
                <Text
                  className="text-[11px] text-general-200"
                  numberOfLines={1}
                >
                  {!state || state.status === "loading"
                    ? "searching…"
                    : state.status === "empty"
                      ? "none nearby"
                      : state.place.distanceMeters != null
                        ? `${Math.round(state.place.distanceMeters / 100) / 10} km away`
                        : state.place.name}
                </Text>
              </View>
            </TouchableOpacity>
          );
        })}
      </ScrollView>
    </View>
  );
};