import ProjectCard from "@/components/cards/ProjectCard";
import ProjectCardSkeleton from "@/components/cards/ProjectCardSkeleton";
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 { Project } 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 First" },
  { value: "created_at-asc", name: "Oldest First" },
  { value: "roi-desc", name: "ROI (H to L)" },
  { value: "roi-asc", name: "ROI (L to H)" },
  { value: "share_value-desc", name: "Share Value (H to L)" },
  { value: "share_value-asc", name: "Share Value (L to H)" },
  { value: "share_sold-desc", name: "Shares Sold (H to L)" },
  { value: "share_sold-asc", name: "Shares Sold (L to H)" },
];

const ProjectItem = memo(function ProjectItem({ item }: { item: Project }) {
  return (
    <View className="px-4 pb-6">
      <ProjectCard project={item} />
    </View>
  );
});

export default function ProjectsScreen() {
  const insets = useSafeAreaInsets();
  const { primary } = useColor();
  const loadingMoreRef = useRef(false);
  const [page, setPage] = useState(1);
  const [items, setItems] = useState<Project[]>([]);
  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 } = 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: projects,
    isLoading,
    isFetching,
    refetch,
  } = useGetQuery({
    url: "/projects",
    params: {
      page: page,
      search: debouncedSearch || undefined,
      type: selectedType || undefined,
      city: selectedCity || undefined,
      orderby: orderBy || undefined,
    },
  });

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

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

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

  const cities = 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 (projects?.data) {
      if (projects.current_page === 1) {
        setItems(projects.data);
      } else {
        setItems((prev) => [...prev, ...projects.data]);
      }
      setHasMore(projects.data.length > 0 && projects.current_page < projects.last_page);
      loadingMoreRef.current = false;
    }
  }, [projects]);

  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">
          <ProjectCardSkeleton />
        </View>
      ) : (
        <ProjectItem item={item as Project} />
      ),
    [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 projects...")}
              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 - Even More Compact */}
        <View className="py-1">
          <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={{ gap: 6 }}>
            {categories.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>

      {/* Main List */}
      <FlatList
        data={isLoading ? [1, 2, 3] : items}
        keyExtractor={keyExtractor}
        renderItem={renderItem}
        onEndReached={loadMore}
        onEndReachedThreshold={0.5}
        showsVerticalScrollIndicator={false}
        contentContainerStyle={{ paddingTop: 16, paddingBottom: 40 }}
        refreshControl={<RefreshControl refreshing={Boolean(isFetching && page === 1)} onRefresh={onRefresh} tintColor={primary.base} />}
        ListEmptyComponent={
          !isLoading && !isFetching && projects && projects?.data?.length === 0 && projects?.current_page === 1 ? (
            <View className="px-4 mt-4">
              <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-3xl mb-8">
              <Text className="text-slate-400 font-manrope-semibold text-xs">{tran("You've viewed all available projects")}</Text>
            </View>
          ) : (
            <View className="h-10" />
          )
        }
      />

      {/* Filter & Sort Bottom Sheet */}
      <BottomSheet visible={isFilterVisible} onClose={() => setIsFilterVisible(false)} title={tran("Filter & Sort")} subtitle={tran("Refine your investment search")} scrollable>
        <View className="pb-10">
          {/* Sorting Area */}
          <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>

          {/* City Selection Area */}
          <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">
            {cities.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>

          {/* Action Buttons */}
          <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>
  );
}
