/**
 * useCertificates Hooks
 * TanStack Query hooks for certificate functionality
 * OQI-002: Modulo Educativo
 */

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

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

export const certificateKeys = {
  all: ['certificates'] as const,
  list: () => [...certificateKeys.all, 'list'] as const,
  detail: (id: string) => [...certificateKeys.all, id] as const,
  byCourse: (courseId: string) => [...certificateKeys.all, 'course', courseId] as const,
  verify: (credentialId: string) => [...certificateKeys.all, 'verify', credentialId] as const,
};

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

export interface CertificateDetail extends EarnedCertificate {
  courseDescription?: string;
  modules?: { title: string; lessonsCompleted: number }[];
  verificationQRCode?: string;
}

export interface SharePlatform {
  platform: 'linkedin' | 'twitter' | 'email' | 'copy';
}

export interface VerificationResult {
  isValid: boolean;
  certificate?: {
    credentialId: string;
    courseTitle: string;
    studentName: string;
    issuedAt: string;
    grade?: number;
  };
  message?: string;
}

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

async function fetchMyCertificates(): Promise<EarnedCertificate[]> {
  const response = await api.get<ApiResponse<EarnedCertificate[]>>('/education/my/certificates');
  return response.data.data;
}

async function fetchCertificateById(id: string): Promise<CertificateDetail> {
  const response = await api.get<ApiResponse<CertificateDetail>>(`/education/certificates/${id}`);
  return response.data.data;
}

async function fetchCertificateByCourse(courseId: string): Promise<EarnedCertificate | null> {
  try {
    const response = await api.get<ApiResponse<EarnedCertificate>>(
      `/education/courses/${courseId}/certificate`
    );
    return response.data.data;
  } catch {
    return null;
  }
}

async function verifyCertificate(credentialId: string): Promise<VerificationResult> {
  const response = await api.get<ApiResponse<VerificationResult>>(
    `/education/certificates/verify/${credentialId}`
  );
  return response.data.data;
}

async function downloadCertificate(id: string): Promise<Blob> {
  const response = await api.get(`/education/certificates/${id}/download`, {
    responseType: 'blob',
  });
  return response.data;
}

async function shareCertificate(
  id: string,
  platform: SharePlatform['platform']
): Promise<{ shareUrl: string }> {
  const response = await api.post<ApiResponse<{ shareUrl: string }>>(
    `/education/certificates/${id}/share`,
    { platform }
  );
  return response.data.data;
}

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

/**
 * Hook to fetch all user certificates
 */
export function useCertificates() {
  return useQuery<EarnedCertificate[], Error>({
    queryKey: certificateKeys.list(),
    queryFn: fetchMyCertificates,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

/**
 * Hook to fetch a certificate by ID
 */
export function useCertificate(id: string) {
  return useQuery<CertificateDetail, Error>({
    queryKey: certificateKeys.detail(id),
    queryFn: () => fetchCertificateById(id),
    enabled: !!id,
    staleTime: 10 * 60 * 1000, // 10 minutes
  });
}

/**
 * Hook to fetch certificate for a specific course
 */
export function useCourseCertificate(courseId: string) {
  return useQuery<EarnedCertificate | null, Error>({
    queryKey: certificateKeys.byCourse(courseId),
    queryFn: () => fetchCertificateByCourse(courseId),
    enabled: !!courseId,
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Hook to verify a certificate
 */
export function useVerifyCertificate(credentialId: string) {
  return useQuery<VerificationResult, Error>({
    queryKey: certificateKeys.verify(credentialId),
    queryFn: () => verifyCertificate(credentialId),
    enabled: !!credentialId,
    staleTime: Infinity, // Verification results don't change
  });
}

/**
 * Hook to download a certificate as PDF
 */
export function useDownloadCertificate() {
  return useMutation<Blob, Error, string>({
    mutationFn: downloadCertificate,
    onSuccess: (blob, id) => {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `certificate-${id}.pdf`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    },
  });
}

/**
 * Hook to share a certificate
 */
export function useShareCertificate() {
  return useMutation<
    { shareUrl: string },
    Error,
    { id: string; platform: SharePlatform['platform'] }
  >({
    mutationFn: ({ id, platform }) => shareCertificate(id, platform),
    onSuccess: ({ shareUrl }, { platform }) => {
      if (platform === 'copy') {
        navigator.clipboard.writeText(shareUrl);
      } else if (platform === 'linkedin') {
        window.open(
          `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(shareUrl)}`,
          '_blank'
        );
      } else if (platform === 'twitter') {
        window.open(
          `https://twitter.com/intent/tweet?url=${encodeURIComponent(shareUrl)}&text=${encodeURIComponent('I just earned a certificate!')}`,
          '_blank'
        );
      } else if (platform === 'email') {
        window.location.href = `mailto:?subject=My Certificate&body=${encodeURIComponent(shareUrl)}`;
      }
    },
  });
}

export default useCertificates;
