import { useNoticesStore } from "@/store/noticesStore";
import { NoticeCard } from "@/components/NoticeCard";
import { Button } from "react-native";
import { Box } from "@/components/ui/box";
import { Text } from "@/components/ui/text";
import { VStack } from "@/components/ui/vstack";
import { ActivityIndicator, FlatList } from "react-native";
import { useEffect, useState } from "react";

export default function UserNotices() {
  const { notices, fetchNotices } = useNoticesStore();
  const [isLoading, setIsLoading] = useState(true);
  const currentUserId = 1; // Tymczasowo, do czasu zaimplementowania logowania bo nie moge pobrac usera

  useEffect(() => {
    const loadNotices = async () => {
      setIsLoading(true);
      try {
        await fetchNotices();
      } catch (err) {
        console.error("Błąd podczas pobierania ogłoszeń:", err);
      } finally {
        setIsLoading(false);
      }
    };
    loadNotices();
  }, []);

  const userNotices = notices
    .filter((notice) => notice.clientId === currentUserId)
    .sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate));

  if (isLoading) {
    return <ActivityIndicator />;
  }

  return (
    <VStack className="p-2">
      {/* <Text className="text-2xl font-bold mb-4">Moje ogłoszenia</Text> */}
      {userNotices.length > 0 ? (
        <FlatList
          data={userNotices}
          // numColumns={1}
          // columnWrapperStyle={{
          //   marginBottom: 10,
          //   justifyContent: "space-between",
          // }}
          renderItem={({ item }) => (
            <Box className="flex-1 mb-4 pb-2 bg-white rounded-lg">
              <NoticeCard notice={item} />
              <Box className="flex-row justify-between mt-2">
                {item.status === "ACTIVE" ? (
                  <Button
                    title="Usuń"
                    onPress={() => {
                      console.log(`Promuj ogłoszenie ${item.noticeId}`);
                    }}
                    className="bg-primary-500 py-2 px-4 rounded-md"
                  ></Button>
                ) : (
                  <Button
                    title="Aktywj"
                    onPress={() => {
                      console.log(`Promuj ogłoszenie ${item.noticeId}`);
                    }}
                    className="bg-primary-500 py-2 px-4 rounded-md"
                  ></Button>
                )}

                <Button
                  title="Podbij"
                  onPress={() => {
                    // TODO: Implementacja podbicia ogłoszenia
                    console.log(`Podbij ogłoszenie ${item.noticeId}`);
                  }}
                  className="bg-primary-500 py-2 px-4 rounded-md"
                ></Button>
              </Box>
            </Box>
          )}
          keyExtractor={(item) => item.noticeId.toString()}
        />
      ) : (
        <Text>Nie masz żadnych ogłoszeń.</Text>
      )}
    </VStack>
  );
}
