import { create } from "zustand";
import * as api from "@/api/notices";

export const useNoticesStore = create((set, get) => ({
  notices: [],
  fetchNotices: async () => {
    set({ error: null });
    try {
      const data = await api.listNotices();
      set({ notices: data });
    } catch (error) {
      set(error);
    }
  },

  addNotice: async (notice) => {
    try {
      const newNotice = await api.createNotice(notice);
      set((state) => ({
        notices: [...state.notices, newNotice],
      }));
      return newNotice;
    } catch (error) {
      set({ error });
      return null;
    }
  },

  editNotice: async (noticeId, notice) => {
    try {
      if (notice.image.length > 0 && typeof notice.image[0] == "string") {
        const currentImages = await api.getAllImagesByNoticeId(noticeId);
        if (currentImages && currentImages.length > 0) {
          for (const image of currentImages) {
            const filename = image.uri
              ? image.uri.split("/").pop()
              : image.split("/").pop();

            await api.deleteImage(filename);
          }
        }
      }
      const updatedNotice = await api.editNotice(noticeId, notice);
      set((state) => ({
        notices: state.notices.map((n) =>
          n.noticeId == noticeId ? updatedNotice : n
        ),
      }));
      return updatedNotice;
    } catch (error) {
      console.error("Error editing notice:", error);
      set({ error });
      throw error;
    }
  },

  getNoticeById: (noticeId) => {
    return get().notices.find(
      (notice) => String(notice.noticeId) === String(noticeId)
    );
  },

  getAllImagesByNoticeId: async (noticeId) => {
    try {
      return await api.getAllImagesByNoticeId(noticeId);
    } catch (error) {
      console.error("Error while getting images:", error);
      return ["https://http.cat/404.jpg"];
    }
  },

  deleteNotice: async (noticeId) => {
    try {
      await api.deleteNotice(noticeId);
      set((state) => ({
        notices: state.notices.filter((notice) => notice.noticeId !== noticeId),
      }));
    } catch (error) {
      console.error("Error deleting notice:", error);
    }
  },
}));
