import MarketplaceCard from "@/components/cards/MarketplaceCard";
import MarketplaceCardSkeleton from "@/components/cards/MarketplaceCardSkeleton";
import BottomSheet from "@/components/ui/BottomSheet";
import NoDataFound from "@/components/ui/no-data-found";
import { useGetQuery } from "@/hooks/mutate/useGetQuery";
import { useColor } from "@/hooks/useColor";
import { useTranslations } from "@/providers/TranslationProviders";
import { ProjectListingData } from "@/types/project";
import { FunnelIcon, MagnifyingGlassIcon, XIcon } from "phosphor-react-native";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ActivityIndicator, FlatList, Pressable, RefreshControl, ScrollView, Text, TextInput, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

const sortOptions = [
  { value: "created_at-desc", name: "Newest Listings" },
  { value: "price-asc", name: "Price (L to H)" },
  { value: "price-desc", name: "Price (H to L)" },
  { value: "number_of_shares-desc", name: "Shares (H to L)" },
  { value: "number_of_shares-asc", name: "Shares (L to H)" },
];

const ListingItem = memo(function ListingItem({ item }: { item: ProjectListingData }) {
  return (
    <View className="px-4 pb-6">
      <MarketplaceCard item={item} />
    </View>
  );
});

export default function MarketPlaceScreen() {
  const insets = useSafeAreaInsets();
  const { primary } = useColor();
  const loadingMoreRef = useRef(false);
  const [page, setPage] = useState(1);
  const [items, setItems] = useState<ProjectListingData[]>([]);
  const [hasMore, setHasMore] = useState(true);
  const [search, setSearch] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const [selectedType, setSelectedType] = useState<string | null>(null);
  const [selectedCity, setSelectedCity] = useState<string | null>(null);
  const [orderBy, setOrderBy] = useState<string>("created_at-desc");
  const [isFilterVisible, setIsFilterVisible] = useState(false);
  const { tran, translateNumber } = useTranslations();

  const activeFilterCount = useMemo(() => {
    let count = 0;
    if (selectedType) count++;
    if (selectedCity) count++;
    if (orderBy !== "created_at-desc") count++;
    return count;
  }, [selectedType, selectedCity, orderBy]);

  const resetFilters = useCallback(() => {
    setSearch("");
    setDebouncedSearch("");
    setSelectedType(null);
    setSelectedCity(null);
    setOrderBy("created_at-desc");
    setPage(1);
  }, []);

  const {
    data: marketplaceData,
    isLoading,
    isFetching,
    refetch,
  } = useGetQuery({
    url: "/marketplace/listings",
    params: {
      page: page,
      search: debouncedSearch || undefined,
      project_type: selectedType || undefined,
      project_location: selectedCity || undefined,
      orderby: orderBy || undefined,
    },
  });

  // Fetch project types for categoriesscroller
  const { data: typesData } = useGetQuery({
    url: "/projects/types",
  });

  // Fetch cities for filters
  const { data: citiesData } = useGetQuery({
    url: "/projects/cities",
  });

  const categoryOptions = useMemo(() => {
    if (!typesData) return [];
    return [{ name: "All", slug: null }, ...typesData] as {
      name: string;
      slug: string | null;
    }[];
  }, [typesData]);

  const cityOptions = useMemo(() => {
    if (!citiesData) return [];
    return [{ name: "All Cities", slug: null }, ...citiesData] as {
      name: string;
      slug: string | null;
    }[];
  }, [citiesData]);

  // Debounce search
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearch(search);
      setPage(1);
    }, 500);
    return () => clearTimeout(timer);
  }, [search]);

  // Handle data appending
  useEffect(() => {
    if (marketplaceData?.data) {
      if (marketplaceData.current_page === 1) {
        setItems(marketplaceData.data);
      } else {
        setItems((prev) => [...prev, ...marketplaceData.data]);
      }
      setHasMore(marketplaceData.data.length > 0 && marketplaceData.current_page < marketplaceData.last_page);
      loadingMoreRef.current = false;
    }
  }, [marketplaceData]);

  const onRefresh = useCallback(async () => {
    setPage(1);
    await refetch();
  }, [refetch]);

  const loadMore = () => {
    if (!isFetching && hasMore && !loadingMoreRef.current && items.length > 0) {
      loadingMoreRef.current = true;
      setPage((prev) => prev + 1);
    }
  };

  const keyExtractor = useCallback((item: any, index: number) => (typeof item === "object" ? `${item.id}-${index}` : `skeleton-${index}`), []);

  const renderItem = useCallback(
    ({ item }: { item: any }) =>
      isLoading ? (
        <View className="px-4 pb-6">
          <MarketplaceCardSkeleton />
        </View>
      ) : (
        <ListingItem item={item as ProjectListingData} />
      ),
    [isLoading],
  );

  return (
    <View className="flex-1 bg-white" style={{ paddingTop: insets.top }}>
      {/* Super Compact Header */}
      <View className="px-4 pt-2 pb-1 border-b border-slate-50">
        <View className="flex-row items-center gap-3 mb-2">
          {/* Action Bar: Search + Filter */}
          <View className="flex-1 flex-row items-center bg-slate-100 rounded-xl px-3 py-1">
            <MagnifyingGlassIcon size={18} color="#64748b" weight="bold" />
            <TextInput
              className="flex-1 ml-2 font-manrope-medium text-slate-900 text-sm "
              placeholder={tran("Search listings...")}
              value={search}
              onChangeText={setSearch}
              placeholderTextColor="#94a3b8"
            />
            {search.length > 0 && (
              <Pressable onPress={() => setSearch("")} hitSlop={8} className="p-1">
                <View pointerEvents="none">
                  <XIcon size={14} color="#64748b" weight="bold" />
                </View>
              </Pressable>
            )}
          </View>

          <Pressable onPress={() => setIsFilterVisible(true)} className={`p-4 rounded-xl relative ${activeFilterCount > 0 ? "bg-slate-900" : "bg-slate-50"}`}>
            <View pointerEvents="none">
              <FunnelIcon size={18} color={activeFilterCount > 0 ? "white" : "#64748b"} weight="bold" />
            </View>
            {activeFilterCount > 0 && (
              <View className="absolute -top-1 -right-1 w-4 h-4 rounded-full items-center justify-center border-2 border-white shadow-sm" style={{ backgroundColor: primary.base }}>
                <Text className="text-white text-[8px] font-manrope-bold">{activeFilterCount}</Text>
              </View>
            )}
          </Pressable>
        </View>

        {/* Categories Scroller */}
        <View className="py-1">
          <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={{ gap: 6 }}>
            {categoryOptions.map((cat) => {
              const isActive = selectedType === cat.slug;
              return (
                <Pressable
                  key={cat.slug || "all"}
                  onPress={() => {
                    setSelectedType(cat.slug);
                    setPage(1);
                  }}
                  className={`px-3.5 py-1.5 rounded-lg border ${isActive ? "bg-slate-900 border-slate-900" : "bg-white border-slate-100"}`}
                >
                  <Text className={`font-manrope-bold text-[11px] ${isActive ? "text-white" : "text-slate-500"}`}>{tran(cat.name)}</Text>
                </Pressable>
              );
            })}
          </ScrollView>
        </View>
      </View>

      {/* Results Count Summary */}
      {!isLoading && items.length > 0 && (
        <View className="px-4 pt-4 pb-2">
          <Text className="text-xs font-manrope-bold text-slate-400 uppercase tracking-widest">
            {translateNumber(marketplaceData?.total || 0)} {tran("Marketplace Listings")}
          </Text>
        </View>
      )}

      {/* Marketplace List */}
      <FlatList
        data={isLoading ? [1, 2, 3] : items}
        keyExtractor={keyExtractor}
        renderItem={renderItem}
        onEndReached={loadMore}
        onEndReachedThreshold={0.5}
        showsVerticalScrollIndicator={false}
        contentContainerStyle={{ paddingTop: 8, paddingBottom: 40 }}
        refreshControl={<RefreshControl refreshing={Boolean(isFetching && page === 1)} onRefresh={onRefresh} tintColor={primary.base} />}
        ListEmptyComponent={
          !isLoading && !isFetching && marketplaceData && marketplaceData?.data?.length === 0 && marketplaceData?.current_page === 1 ? (
            <View className="px-4 mt-8">
              <NoDataFound title={tran("No Match Found")} description={tran("Try resetting your search or adjusting filters.")} bordered={false}>
                <Pressable onPress={resetFilters} className="bg-slate-900 px-8 py-3.5 rounded-2xl shadow-lg flex-row items-center gap-2">
                  <View pointerEvents="none">
                    <FunnelIcon size={20} color="white" weight="bold" />
                  </View>
                  <Text className="text-white font-manrope-bold text-lg">{tran("Reset All")}</Text>
                </Pressable>
              </NoDataFound>
            </View>
          ) : null
        }
        ListFooterComponent={
          isFetching && page > 1 ? (
            <View className="py-8">
              <ActivityIndicator color={primary.base} size="small" />
            </View>
          ) : !hasMore && items.length > 0 ? (
            <View className="py-12 items-center bg-slate-50 mx-4 rounded-[40px] mb-8">
              <Text className="text-slate-400 font-manrope-semibold text-xs">{tran("You've viewed all marketplace listings")}</Text>
            </View>
          ) : (
            <View className="h-10" />
          )
        }
      />

      {/* Filter & Sort Bottom Sheet */}
      <BottomSheet visible={isFilterVisible} onClose={() => setIsFilterVisible(false)} title={tran("Filter & Sort")} subtitle={tran("Refine your marketplace search")} scrollable>
        <View className="pb-10">
          <Text className="text-lg font-manrope-bold text-slate-900 mb-4">{tran("Sort By")}</Text>
          <View className="flex-row flex-wrap gap-2 mb-8">
            {sortOptions.map((opt) => {
              const isActive = orderBy === opt.value;
              return (
                <Pressable
                  key={opt.value}
                  onPress={() => setOrderBy(opt.value)}
                  className={`px-4 py-2.5 rounded-xl border-2 ${isActive ? "bg-slate-900 border-slate-900" : "bg-white border-slate-100"}`}
                >
                  <Text className={`text-sm ${isActive ? "font-manrope-bold text-white" : "font-manrope-medium text-slate-600"}`}>{tran(opt.name)}</Text>
                </Pressable>
              );
            })}
          </View>

          <Text className="text-lg font-manrope-bold text-slate-900 mb-4">{tran("Select City")}</Text>
          <View className="flex-row flex-wrap gap-2 mb-8">
            {cityOptions.map((city) => {
              const isActive = selectedCity === city.slug;
              return (
                <Pressable
                  key={city.slug || "all-cities"}
                  onPress={() => setSelectedCity(city.slug)}
                  className={`px-4 py-2.5 rounded-xl border-2 ${isActive ? "bg-slate-900 border-slate-900" : "bg-white border-slate-100"}`}
                >
                  <Text className={`text-sm ${isActive ? "font-manrope-bold text-white" : "font-manrope-medium text-slate-600"}`}>{tran(city.name)}</Text>
                </Pressable>
              );
            })}
          </View>

          <View className="flex-row gap-4 pt-4 border-t border-slate-50">
            <Pressable onPress={resetFilters} className="flex-1 py-4 border border-slate-200 rounded-2xl items-center">
              <Text className="font-manrope-bold text-slate-600">{tran("Reset All")}</Text>
            </Pressable>
            <Pressable
              onPress={() => {
                setPage(1);
                setIsFilterVisible(false);
              }}
              style={{
                backgroundColor: primary.base,
              }}
              className="flex-2 py-4 rounded-2xl items-center px-10"
            >
              <Text className="font-manrope-bold text-white">{tran("Apply Filters")}</Text>
            </Pressable>
          </View>
        </View>
      </BottomSheet>
    </View>
  );
}
