import { useState, useEffect } from "react";
import {
Image,
StyleSheet,
KeyboardAvoidingView,
Platform,
ActivityIndicator,
} from "react-native";
import { Button, ButtonText } from "@/components/ui/button";
import { FormControl } from "@/components/ui/form-control";
import { Input, InputField } from "@/components/ui/input";
import { Text } from "@/components/ui/text";
import { VStack } from "@/components/ui/vstack";
import { Textarea, TextareaInput } from "@/components/ui/textarea";
import { ScrollView } from "@gluestack-ui/themed";
import { Box } from "@/components/ui/box";
import * as ImagePicker from "expo-image-picker";
import {
Select,
SelectTrigger,
SelectInput,
SelectIcon,
SelectPortal,
SelectBackdrop,
SelectContent,
SelectItem,
SelectScrollView,
} from "@/components/ui/select";
import { ChevronDownIcon } from "@/components/ui/icon";
import { useNoticesStore } from "@/store/noticesStore";
import { listCategories } from "@/api/categories";
import { useRouter } from "expo-router";
import { attributes } from "@/data/attributesData";
import { useLocalSearchParams } from "expo-router";
export default function EditNotice() {
const { id } = useLocalSearchParams();
const router = useRouter();
const { editNotice, fetchNotices, notices } = useNoticesStore();
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [price, setPrice] = useState("");
const [category, setCategory] = useState("");
const [image, setImage] = useState([]);
const [isImageLoading, setIsImageLoading] = useState(true);
const [selectItems, setSelectItems] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [selectedAttributes, setSelectedAttributes] = useState({});
const { getNoticeById, getAllImagesByNoticeId } = useNoticesStore();
useEffect(() => {
let isMounted = true;
const fetchSelectItems = async () => {
try {
let data = await listCategories();
if (isMounted && Array.isArray(data)) {
setSelectItems(data);
}
} catch (error) {
console.error("Error fetching select items:", error);
}
};
fetchSelectItems();
return () => {
isMounted = false;
};
}, []);
useEffect(() => {
const notice = notices.find((notice) => notice.noticeId == id);
if (notice) {
setTitle(notice.title || "");
setDescription(notice.description || "");
setPrice(notice.price?.toString() || "");
setCategory(notice.category || "");
if (notice.attributes && Array.isArray(notice.attributes)) {
const attributesObj = {};
notice.attributes.forEach((attr) => {
attributesObj[attr.name] = attr.value;
});
setSelectedAttributes(attributesObj);
}
}
const fetchImage = async () => {
setIsImageLoading(true);
try {
const fetchedImages = await getAllImagesByNoticeId(notice.noticeId);
if (fetchedImages && fetchedImages.length > 0) {
setImage(fetchedImages);
} else {
setImage([]);
}
} catch (err) {
console.error("Error while loading images:", err);
setImage([]);
} finally {
setIsImageLoading(false);
}
};
if (notice) {
fetchImage();
}
}, [notices, id]);
const [error, setError] = useState({
title: false,
description: false,
price: false,
category: false,
});
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
image: {
width: 100,
height: 100,
},
});
const handleEditNotice = async () => {
setError({
title: !title,
description: !description,
price: !price,
category: !category,
});
if (!title || !description || !price || !category) {
console.log("Error in form");
return;
}
const formattedAttributes = Object.entries(selectedAttributes).map(
([name, value]) => ({
name: name,
value: value,
})
);
setIsLoading(true);
try {
const result = await editNotice(id, {
title: title,
description: description,
price: price,
category: category,
status: "INACTIVE",
image: image,
attributes: formattedAttributes,
});
if (result) {
await fetchNotices();
router.push("/(tabs)/dashboard/userNotices");
}
} catch (error) {
console.error("Error editing notice. Error message: ", error.message);
} finally {
setIsLoading(false);
}
};
const takePicture = async () => {
const { status } = await ImagePicker.requestCameraPermissionsAsync();
if (status !== "granted") {
return;
}
const result = await ImagePicker.launchCameraAsync({
allowsEditing: false,
});
if (!result.canceled && result.assets) {
setImage(result.assets.map((asset) => asset.uri));
}
};
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: "images",
selectionLimit: 8,
allowsEditing: false,
allowsMultipleSelection: true,
aspect: [4, 3],
quality: 0.5,
});
if (!result.canceled) {
setImage(result.assets.map((asset) => asset.uri));
}
};
if (isLoading) {
return (
Edytuj ogłoszenie...
);
}
return (
Zdjęcia
Pierwsze zdjęcie będzie zdjęciem głównym
{image && image.length > 0 && (
{image.map((img, index) => {
const imageSource =
typeof img === "string" ? { uri: img } : img;
return (
console.log(`Image ${index} error:`, error)
}
/>
);
})}
)}
Tytuł*
setTitle(value)}
/>
Opis*
Cena*
setPrice(value)}
/>
Kategoria*
{Object.entries(attributes).map(([label, options]) => (
{label}
))}
);
}