'use client';

import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import type { NextcloudFile } from '@/types/integrations';

/** Query key factory */
export const filesKeys = {
  all: ['files'] as const,
  list: (path?: string) => [...filesKeys.all, 'list', path] as const,
  recent: ['files', 'recent'] as const,
};

interface FetchFilesParams {
  path?: string;
  limit?: number;
}

/**
 * Fetch Nextcloud files
 */
async function fetchFiles(params?: FetchFilesParams): Promise<NextcloudFile[]> {
  const queryParams: Record<string, string | number | boolean | undefined> = {};
  if (params?.path) queryParams.path = params.path;

  const response = await api.get<NextcloudFile[]>(
    '/integrations/nextcloud/files',
    { params: queryParams },
  );
  const files = Array.isArray(response) ? response : [];

  if (params?.limit) {
    return files.slice(0, params.limit);
  }
  return files;
}

/**
 * Fetch recently modified files
 */
async function fetchRecentFiles(limit = 5): Promise<NextcloudFile[]> {
  return api.get<NextcloudFile[]>(
    '/integrations/nextcloud/files/recent',
    { params: { limit } },
  );
}

/**
 * Hook to fetch Nextcloud files
 */
export function useFiles(params?: FetchFilesParams) {
  return useQuery({
    queryKey: filesKeys.list(params?.path),
    queryFn: () => fetchFiles(params),
    staleTime: 30 * 1000,
    refetchOnWindowFocus: true,
  });
}

/**
 * Hook to fetch recently modified files
 */
export function useRecentFiles(limit = 5) {
  return useQuery({
    queryKey: filesKeys.recent,
    queryFn: () => fetchRecentFiles(limit),
    staleTime: 30 * 1000,
    refetchOnWindowFocus: true,
  });
}

/**
 * Format file size for display
 */
export function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
}

/**
 * Get file icon based on mime type
 */
export function getFileIcon(mimeType?: string): string {
  if (!mimeType) return 'file';

  if (mimeType.startsWith('image/')) return 'image';
  if (mimeType.startsWith('video/')) return 'video';
  if (mimeType.startsWith('audio/')) return 'audio';
  if (mimeType.includes('pdf')) return 'file-text';
  if (mimeType.includes('spreadsheet') || mimeType.includes('excel')) return 'table';
  if (mimeType.includes('document') || mimeType.includes('word')) return 'file-text';
  if (mimeType.includes('presentation') || mimeType.includes('powerpoint')) return 'presentation';
  if (mimeType.includes('zip') || mimeType.includes('compressed')) return 'archive';

  return 'file';
}
