import { supabase } from '@/lib/supabase'
import { EASE, computeNextReview, statusFor, type EaseKey } from '../lib/srs-intervals'

export interface FlashcardList {
  id: number
  title: string
  description: string | null
  total_words: number
  is_public: boolean
  created_by: string | null
  created_at: string
  // aggregated from user progress
  count_new?: number
  count_learning?: number
  count_known?: number
  progress_pct?: number
}

export interface FlashcardTerm {
  id: number
  list_id: number
  word: string
  part_of_speech: string | null
  phonetic: string | null
  definition: string | null
  example: string | null
  image_url: string | null
  audio_tts_text: string | null
  audio_lang: string | null
  display_order: number
}

export interface UserProgress {
  id: number
  user_id: string
  term_id: number
  list_id: number
  status: 'new' | 'learning' | 'known' | 'ignored'
  ease_factor: number
  review_count: number
  last_reviewed_at: string | null
  next_review_at: string | null
}

/** Fetch all public flashcard lists with term counts */
export async function fetchFlashcardLists(): Promise<FlashcardList[]> {
  const { data, error } = await supabase
    .from('flashcard_list')
    .select('id, title, description, total_words, is_public, created_by, created_at')
    .order('created_at', { ascending: false })
  if (error) throw error
  return data ?? []
}

/** Fetch all terms for a flashcard list */
export async function fetchFlashcardTerms(listId: number): Promise<FlashcardTerm[]> {
  const { data, error } = await supabase
    .from('flashcard_term')
    .select('id, list_id, word, part_of_speech, phonetic, definition, example, image_url, audio_tts_text, audio_lang, display_order')
    .eq('list_id', listId)
    .order('display_order', { ascending: true })
  if (error) throw error
  return data ?? []
}

/** Fetch user progress for all terms in a list */
export async function fetchUserProgress(userId: string, listId: number): Promise<UserProgress[]> {
  const { data, error } = await supabase
    .from('user_flashcard_progress')
    .select('id, user_id, term_id, list_id, status, ease_factor, review_count, last_reviewed_at, next_review_at')
    .eq('user_id', userId)
    .eq('list_id', listId)
  if (error) throw error
  return data ?? []
}

/** Upsert user progress for a term. Increments review_count, writes next_review_at via interval ladder. */
export async function upsertTermProgress(
  userId: string,
  termId: number,
  listId: number,
  easeKey: EaseKey,
  currentReviewCount: number,
): Promise<void> {
  const now = new Date().toISOString()
  const nextReview = computeNextReview(easeKey, currentReviewCount)

  const { error } = await supabase
    .from('user_flashcard_progress')
    .upsert(
      {
        user_id: userId,
        term_id: termId,
        list_id: listId,
        status: statusFor(easeKey),
        ease_factor: EASE[easeKey],
        review_count: currentReviewCount + 1,
        last_reviewed_at: now,
        next_review_at: nextReview,
      },
      { onConflict: 'user_id,term_id,list_id' },
    )
  if (error) console.error('upsertTermProgress failed:', error.message)
}

export interface LearnSession {
  id: number
  user_id: string
  list_id: number
  started_at: string
}

export async function startSession(userId: string, listId: number): Promise<LearnSession> {
  const { data, error } = await supabase
    .from('user_flashcard_session')
    .insert({ user_id: userId, list_id: listId })
    .select('id, user_id, list_id, started_at')
    .single()
  if (error) throw error
  return data as LearnSession
}

export async function endSession(
  sessionId: number,
  termsReviewed: number,
  termsNew: number,
): Promise<void> {
  const { error } = await supabase
    .from('user_flashcard_session')
    .update({
      ended_at: new Date().toISOString(),
      terms_reviewed: termsReviewed,
      terms_new: termsNew,
    })
    .eq('id', sessionId)
  if (error) console.error('endSession failed:', error.message)
}

export async function logReview(
  sessionId: number,
  userId: string,
  termId: number,
  actionValue: number,
): Promise<void> {
  const { error } = await supabase
    .from('user_flashcard_review_log')
    .insert({
      session_id: sessionId,
      user_id: userId,
      term_id: termId,
      action_value: actionValue,
    })
  if (error) console.error('logReview failed:', error.message)
}
