import { create } from "zustand"
import axiosInstance from "@/utils/axios"
import { documentEndpoints } from "../../endpoints/document-service"
import type { NewFolderRequest, FolderDTO, FolderDetails } from "../../../types/document"

type FolderStore = {
  loading: boolean
  error: string | null
  createdFolder: FolderDTO | null
  createFolder: (folder: NewFolderRequest) => Promise<void>
  getRootFolders: (ownerUuid : string) => Promise<FolderDTO[]>
  renameFolder: (folderId: number, newName: string, ownerUuid : string) => Promise<FolderDTO | null>
  moveFolder: (folderId: number, newParentId: number | null, ownerUuid : string) => Promise<void>
  deleteFolder: (folderId: number, ownerUuid : string) => Promise<void>
  searchFolders: (keyword: string, ownerUuid : string) => Promise<FolderDTO[]>
  getFolderDetails: (folderId: number, ownerUuid : string) => Promise<FolderDetails | null>
  downloadZip: (folderId: number, folderName: string, ownerUuid : string) => Promise<void>
  toggleFavorite: (folderId: number, ownerUuid : string) => Promise<FolderDTO>
  toggleUnfavorite: (folderId: number, ownerUuid : string) => Promise<FolderDTO>
}

export const useFolderStore = create<FolderStore>((set) => ({
  loading: false,
  error: null,
  createdFolder: null,

  createFolder: async (folderData: NewFolderRequest) => {
    set({ loading: true, error: null })
    try {
      const response = await axiosInstance.post<FolderDTO>(documentEndpoints.Folder.create, folderData)
      set({ createdFolder: response.data, loading: false })
    } catch (error: any) {
      set({
        error: error.message || "Failed to create folder",
        loading: false,
      })
    }
  },
  getRootFolders: async (ownerUuid : string) => {
    set({ loading: true, error: null })
    try {
      const response = await axiosInstance.get<FolderDTO[]>(documentEndpoints.Folder.getUserRootFolders(ownerUuid))
      set({ loading: false })
      return response.data
    } catch (error: any) {
      set({
        error: error.message || "Failed to get root folders",
        loading: false,
      })
      return []
    }
  },
  renameFolder: async (folderId: number, newName: string, ownerUuid : string) => {
    set({ loading: true, error: null })
    try {
      const response = await axiosInstance.put<FolderDTO>(
        documentEndpoints.Folder.rename(folderId, newName, ownerUuid)
      )
      set({ loading: false })
      return response.data
    } catch (error: any) {
      set({
        error: error.message || "Failed to rename folder",
        loading: false,
      })
      return null
    }
  },
  moveFolder: async (folderId, newParentId, ownerUuid) => {
    set({ loading: true, error: null });
    try {
      await axiosInstance.put(
        `${documentEndpoints.Folder.move}/${folderId}`,
        null,
        { params: { newParentId, ownerUuid } }
      );
      set({ loading: false });
    } catch (error: any) {
      set({
        error: error.message || "Failed to move folder",
        loading: false,
      });
    }
  },
  deleteFolder: async (folderId, ownerUuid) => {
    set({ loading: true, error: null });
    try {
      await axiosInstance.delete(documentEndpoints.Folder.delete(folderId, ownerUuid));
      set({ loading: false });
    } catch (error: any) {
      set({
        error: error.message || "Échec de la suppression du dossier",
        loading: false,
      });
    }
  },
  searchFolders: async (keyword: string, ownerUuid : string): Promise<FolderDTO[]> => {
    set({ loading: true, error: null })
    try {
      const response = await axiosInstance.get<FolderDTO[]>(documentEndpoints.Folder.search, {
        params: { keyword, ownerUuid },
      })
      set({ loading: false })
      return response.data
    } catch (error: any) {
      set({
        error: error.message || "Erreur lors de la recherche de dossiers",
        loading: false,
      })
      return []
    }
  },
  getFolderDetails: async (folderId, ownerUuid) => {
    try {
      const response = await axiosInstance.get<FolderDetails>(documentEndpoints.Folder.getDetails(folderId, ownerUuid));
      return response.data;
    } catch (error: any) {
      console.error("Error fetching folder details", error);
      return null;
    }
  },
  downloadZip: async (folderId: number, folderName: string, ownerUuid: string) => {
  try {
    const response = await axiosInstance.get(documentEndpoints.Folder.downloadZip(folderId, ownerUuid), {
      responseType: 'blob',
    })

    const blob = new Blob([response.data], { type: 'application/zip' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `${folderName}.zip`)
    document.body.appendChild(link)
    link.click()
    link.remove()
  } catch (error: any) {
    console.error('Échec du téléchargement du dossier:', error)
  }
},
  // In folderStore.ts
toggleFavorite: async (folderId: number, ownerUuid : string): Promise<FolderDTO> => {
  const response = await axiosInstance.post<FolderDTO>(
    documentEndpoints.Folder.favorite(folderId, ownerUuid)
  );
  return response.data; // Return updated folder
},

toggleUnfavorite: async (folderId: number, ownerUuid : string): Promise<FolderDTO> => {
  const response = await axiosInstance.delete<FolderDTO>(
    documentEndpoints.Folder.unfavorite(folderId, ownerUuid)
  );
  return response.data; // Return updated folder
},

}))
