import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { apiClient } from '@/api/client'
import { t } from '@/lib/i18n'

export type AIProvider = 'claude' | 'openai'

interface AIModel {
  id: string
  display_name: string
  category: 'sonnet' | 'haiku' | 'opus' | 'gpt' | 'reasoning' | 'other'
  input_price: number
  output_price: number
  created_at?: string
}

interface ModelsResponse {
  success: boolean
  data: {
    models: AIModel[]
    current_model: string
    count: number
    refreshed?: boolean
    message?: string
  }
}

/**
 * Hook to get available AI models (Claude/OpenAI)
 */
export function useModels(provider: AIProvider = 'claude') {
  return useQuery({
    queryKey: ['ai-models', provider],
    queryFn: () =>
      provider === 'openai'
        ? apiClient.get<ModelsResponse>('settings/openai-models')
        : apiClient.get<ModelsResponse>('settings/models'),
    staleTime: 1000 * 60 * 60, // 1 hour
  })
}

/**
 * Hook to refresh models from the provider API
 */
export function useRefreshModels(provider: AIProvider = 'claude') {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: () =>
      provider === 'openai'
        ? apiClient.post<ModelsResponse>('settings/openai-models/refresh', {})
        : apiClient.post<ModelsResponse>('settings/models/refresh', {}),
    onSuccess: (data) => {
      queryClient.setQueryData(['ai-models', provider], data)
    },
  })
}

/**
 * Get category label in Hebrew
 */
export function getCategoryLabel(category: string): string {
  const labels: Record<string, string> = {
    sonnet: t('Sonnet - Perfect Balance'),
    haiku: t('Haiku - Fast & Affordable'),
    opus: t('Opus - Most Intelligent'),
    gpt: 'GPT',
    reasoning: 'Reasoning',
    other: t('Other'),
  }
  return labels[category] || category
}

/**
 * Get category badge color
 */
export function getCategoryColor(category: string): string {
  const colors: Record<string, string> = {
    sonnet: 'bg-primary-100 text-primary-700',
    haiku: 'bg-green-100 text-green-700',
    opus: 'bg-purple-100 text-purple-700',
    gpt: 'bg-blue-100 text-blue-700',
    reasoning: 'bg-amber-100 text-amber-700',
    other: 'bg-gray-100 text-gray-700',
  }
  return colors[category] || 'bg-gray-100 text-gray-700'
}

