import { ScrollView } from "react-native";
import { useNoticesStore } from "@/store/noticesStore";
import { CategorySection } from "@/components/CategorySection";
import { NoticeSection } from "@/components/NoticeSection";
import { UserSection } from "@/components/UserSection";
import { SearchSection } from "@/components/SearchSection";
import { useAuthStore } from "@/store/authStore";
import { useRouter } from "expo-router";
import { useEffect, useState } from "react";
import { SafeAreaView } from "react-native";

export default function Home() {
  const { token } = useAuthStore.getState();
  const router = useRouter();
  const [isReady, setIsReady] = useState(false);
  const fetchNotices = useNoticesStore((state) => state.fetchNotices);

  useEffect(() => {
    setIsReady(true);
  }, []);

  useEffect(() => {
    if (isReady && !token) {
      router.replace("/login");
    }
  }, [isReady, token, router]);

  useEffect(() => {
    if (token) {
      fetchNotices();
    }
  }, [token]);

  const notices = useNoticesStore((state) => state.notices);

  const activeNotices = notices.filter((notice) => notice.status === "ACTIVE");
  const latestNotices = [...activeNotices]
    .sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate))
    .slice(0, 6);
  const recomendedNotices = [...activeNotices]
    .sort(() => Math.random() - 0.5)
    .slice(0, 6);

  return (
    <SafeAreaView className="flex-1 m-2">
      {/* <View>    */}
      <SearchSection />
      <ScrollView showsVerticalScrollIndicator={false}>
        <CategorySection title="Polecane kategorie" notices={activeNotices} />
        <NoticeSection
          title="Najnowsze ogłoszenia"
          notices={latestNotices}
          ctaLink="/notices?sort=latest"
        />
        <UserSection title="Popularni sprzedawcy" notices={activeNotices} />
        <NoticeSection
          title="Proponowane ogłoszenia"
          notices={recomendedNotices}
          ctaLink="/notices"
        />
      </ScrollView>
      {/* </View> */}
    </SafeAreaView>
  );
}
