import {Stack, useLocalSearchParams} from "expo-router";
import {Box} from "@/components/ui/box";
import {Card} from "@/components/ui/card";
import {Heading} from "@/components/ui/heading";
import {Image} from "@/components/ui/image";
import {Text} from "@/components/ui/text";
import {VStack} from "@/components/ui/vstack";
import {Ionicons} from "@expo/vector-icons";
import {ActivityIndicator} from "react-native";
import {useEffect, useState} from "react";
import {useNoticesStore} from "@/store/noticesStore";
import {useWishlist} from "@/store/wishlistStore";
import {Pressable} from "react-native";

export default function NoticeDetails() {
    const {id} = useLocalSearchParams();
    const [image, setImage] = useState(null);
    const [isImageLoading, setIsImageLoading] = useState(true);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);
    const [notice, setNotice] = useState(null);

    const {getNoticeById, getAllImagesByNoticeId} = useNoticesStore();
    const addNoticeToWishlist = useWishlist((state) => state.addNoticeToWishlist);
    const removeNoticeFromWishlist = useWishlist((state) => state.removeNoticeFromWishlist);
    const isInWishlist = useWishlist((state) =>
        notice ? state.wishlistNotices.some((item) => item.noticeId === notice.noticeId) : false
    );

    useEffect(() => {
        const fetchNotice = async () => {
            setIsLoading(true);
            try {
                const noticeData = getNoticeById(Number(id));
                if (noticeData) {
                    setNotice(noticeData);
                    setError(null);
                } else {
                    setError(new Error(`Notice with ID ${id} not found.`));
                }
            } catch (err) {
                setError(err);
            } finally {
                setIsLoading(false);
            }
        };

        fetchNotice();
    }, [id]);

    useEffect(() => {
        const fetchImage = async () => {
            setIsImageLoading(true);
            if (notice) {
                try {
                    const images = await getAllImagesByNoticeId(notice.noticeId);
                    setImage(images && images.length > 0 ? images[0] : "https://http.cat/404.jpg");
                } catch (err) {
                    console.error("Error while loading images:", err);
                    setImage("https://http.cat/404.jpg");
                } finally {
                    setIsImageLoading(false);
                }
            }
        };

        if (notice) {
            fetchImage();
        }
    }, [notice]);

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

    if (error) {
        return <Text>Błąd, spróbuj ponownie póżniej: {error.message}</Text>;
    }

    if (!notice) {
        return <Text>Nie znaleziono ogłoszenia</Text>;
    }

    return (
        <Card className="p-0 rounded-lg m-3 flex-1">
            <Stack.Screen
                options={{
                    title: notice.title,
                }}
            />
            {isImageLoading ? (
                <Box className="h-auto w-full rounded-md aspect-[1/1] bg-gray-100 items-center justify-center">
                    <ActivityIndicator size="large" color="#3b82f6" />
                </Box>
            ) : (
                <Image
                    source={{
                        uri: image,
                    }}
                    className="h-auto w-full rounded-md aspect-[1/1]"
                    alt="image"
                    resizeMode="cover"
                />
            )}

            <VStack className="p-2">
                <Text className="text-sm font-normal mb-2 text-typography-700">
                    {notice.title}
                </Text>
                <Box className="flex-row items-center">
                    <Heading size="md" className="flex-1">
                        {notice.price}zł
                    </Heading>
                    <Pressable
                        onPress={() => {
                            if (isInWishlist) {
                                removeNoticeFromWishlist(notice.noticeId);
                            } else {
                                addNoticeToWishlist(notice);
                            }
                        }}
                    >
                        <Ionicons
                            name={isInWishlist ? "heart" : "heart-outline"}
                            size={24}
                            color={"primary-heading-500"}
                        />
                    </Pressable>
                </Box>
            </VStack>
        </Card>
    );
}