import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { foldersApi, AssetFolder } from '@/services/api/assets.api';
import { useToast } from '@/hooks/use-toast';

export function useFolders(brandId?: string) {
  return useQuery({
    queryKey: ['folders', { brandId }],
    queryFn: () => foldersApi.getAll(brandId).then((res) => res.data),
  });
}

export function useFolderTree(brandId?: string) {
  return useQuery({
    queryKey: ['folders', 'tree', { brandId }],
    queryFn: () => foldersApi.getTree(brandId).then((res) => res.data),
  });
}

export function useRootFolders(brandId?: string) {
  return useQuery({
    queryKey: ['folders', 'root', { brandId }],
    queryFn: () => foldersApi.getRootFolders(brandId).then((res) => res.data),
  });
}

export function useFolder(id: string) {
  return useQuery({
    queryKey: ['folders', id],
    queryFn: () => foldersApi.getById(id).then((res) => res.data),
    enabled: !!id,
  });
}

export function useFolderBySlug(slug: string) {
  return useQuery({
    queryKey: ['folders', 'slug', slug],
    queryFn: () => foldersApi.getBySlug(slug).then((res) => res.data),
    enabled: !!slug,
  });
}

export function useCreateFolder() {
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: (data: Partial<AssetFolder>) => foldersApi.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['folders'] });
      toast({ title: 'Carpeta creada exitosamente' });
    },
    onError: (error: any) => {
      toast({
        title: 'Error al crear carpeta',
        description: error.response?.data?.message || 'Error desconocido',
        variant: 'destructive',
      });
    },
  });
}

export function useUpdateFolder() {
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<AssetFolder> }) =>
      foldersApi.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['folders'] });
      toast({ title: 'Carpeta actualizada exitosamente' });
    },
    onError: (error: any) => {
      toast({
        title: 'Error al actualizar carpeta',
        description: error.response?.data?.message || 'Error desconocido',
        variant: 'destructive',
      });
    },
  });
}

export function useDeleteFolder() {
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: (id: string) => foldersApi.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['folders'] });
      toast({ title: 'Carpeta eliminada exitosamente' });
    },
    onError: (error: any) => {
      toast({
        title: 'Error al eliminar carpeta',
        description: error.response?.data?.message || 'Error desconocido',
        variant: 'destructive',
      });
    },
  });
}
