/**
 * useCourseProgress Hook
 * TanStack Query hook for course progress tracking
 * OQI-002: Modulo Educativo
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient as api } from '../../../lib/apiClient';
import type { CourseProgressData, ModuleProgress } from '../components/CourseProgressTracker';
import type { ApiResponse } from '../../../types/education.types';

// ============================================================================
// Query Keys
// ============================================================================

export const courseProgressKeys = {
  all: ['course-progress'] as const,
  detail: (courseId: string) => [...courseProgressKeys.all, courseId] as const,
  stats: (courseId: string) => [...courseProgressKeys.all, courseId, 'stats'] as const,
  modules: (courseId: string) => [...courseProgressKeys.all, courseId, 'modules'] as const,
  continue: () => [...courseProgressKeys.all, 'continue'] as const,
};

// ============================================================================
// Types
// ============================================================================

export interface ContinueLearning {
  courseId: string;
  courseTitle: string;
  courseSlug: string;
  courseThumbnail?: string;
  lastLessonId: string;
  lastLessonTitle: string;
  progressPercentage: number;
  lastAccessedAt: string;
}

// ============================================================================
// API Functions
// ============================================================================

async function fetchCourseProgress(courseId: string): Promise<CourseProgressData> {
  const response = await api.get<ApiResponse<CourseProgressData>>(
    `/education/courses/${courseId}/progress`
  );
  return response.data.data;
}

async function fetchContinueLearning(): Promise<ContinueLearning | null> {
  try {
    const response = await api.get<ApiResponse<ContinueLearning>>('/education/my/continue');
    return response.data.data;
  } catch {
    return null;
  }
}

async function downloadProgressReport(courseId: string): Promise<Blob> {
  const response = await api.get(`/education/courses/${courseId}/progress/report`, {
    responseType: 'blob',
  });
  return response.data;
}

// ============================================================================
// Hooks
// ============================================================================

/**
 * Hook to fetch course progress data
 */
export function useCourseProgress(courseId: string) {
  return useQuery<CourseProgressData, Error>({
    queryKey: courseProgressKeys.detail(courseId),
    queryFn: () => fetchCourseProgress(courseId),
    enabled: !!courseId,
    staleTime: 60 * 1000, // 1 minute
    gcTime: 5 * 60 * 1000, // 5 minutes
  });
}

/**
 * Hook to fetch continue learning suggestion
 */
export function useContinueLearning() {
  return useQuery<ContinueLearning | null, Error>({
    queryKey: courseProgressKeys.continue(),
    queryFn: fetchContinueLearning,
    staleTime: 30 * 1000, // 30 seconds
  });
}

/**
 * Hook to download progress report
 */
export function useDownloadProgressReport() {
  return useMutation<Blob, Error, string>({
    mutationFn: downloadProgressReport,
    onSuccess: (blob, courseId) => {
      // Create download link
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `progress-report-${courseId}.pdf`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    },
  });
}

export default useCourseProgress;
