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: (ownerId: number) => Promise<FolderDTO[]>
  renameFolder: (folderId: number, newName: string, ownerId: number) => Promise<FolderDTO | null>
  moveFolder: (folderId: number, newParentId: number | null, ownerId: number) => Promise<void>
  deleteFolder: (folderId: number, ownerId: number) => Promise<void>
  searchFolders: (keyword: string, ownerId: number) => Promise<FolderDTO[]>
  getFolderDetails: (folderId: number) => Promise<FolderDetails | null>
  downloadZip: (folderId: number, folderName: string) => Promise<void>
  toggleFavorite: (folderId: number, userId : number) => Promise<void>
  toggleUnfavorite: (folderId: number, userId : number) => Promise<void>
}

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 (ownerId: number) => {
    set({ loading: true, error: null })
    try {
      const response = await axiosInstance.get<FolderDTO[]>(documentEndpoints.Folder.getUserRootFolders(ownerId))
      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, ownerId: number) => {
    set({ loading: true, error: null })
    try {
      const response = await axiosInstance.put<FolderDTO>(
        documentEndpoints.Folder.rename(folderId, newName, ownerId)
      )
      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, ownerId) => {
    set({ loading: true, error: null });
    try {
      await axiosInstance.put(
        `${documentEndpoints.Folder.move}/${folderId}`,
        null,
        { params: { newParentId, ownerId } }
      );
      set({ loading: false });
    } catch (error: any) {
      set({
        error: error.message || "Failed to move folder",
        loading: false,
      });
    }
  },
  deleteFolder: async (folderId, ownerId) => {
    set({ loading: true, error: null });
    try {
      await axiosInstance.delete(documentEndpoints.Folder.delete(folderId, ownerId));
      set({ loading: false });
    } catch (error: any) {
      set({
        error: error.message || "Échec de la suppression du dossier",
        loading: false,
      });
    }
  },
  searchFolders: async (keyword: string, ownerId: number): Promise<FolderDTO[]> => {
    set({ loading: true, error: null })
    try {
      const response = await axiosInstance.get<FolderDTO[]>(documentEndpoints.Folder.search, {
        params: { keyword, ownerId },
      })
      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) => {
    try {
      const response = await axiosInstance.get<FolderDetails>(documentEndpoints.Folder.getDetails(folderId));
      return response.data;
    } catch (error: any) {
      console.error("Error fetching folder details", error);
      return null;
    }
  },
  downloadZip: async (folderId: number, folderName: string) => {
  try {
    const response = await axiosInstance.get(documentEndpoints.Folder.downloadZip(folderId), {
      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)
  }
},
  toggleFavorite: async (folderId: number, userId: number) => {
    await axiosInstance.post(documentEndpoints.Folder.favorite(folderId), { params: { userId },});
  },
  toggleUnfavorite: async (folderId: number, userId : number) => {
    await axiosInstance.post(documentEndpoints.Folder.unfavorite(folderId), { params: { userId },});
  },

}))
