import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { parseFile, type ParsedTranscription } from '@/services/parse-transcription'
import { analyzeTranscription, type AIExtractedHU, type AIAnalysisResult } from '@/services/ai'
import { kappa } from '@/services/kappa-api'
import { useWorkItemsStore } from '@/stores/workitems'
import { useProjectsStore } from '@/stores/projects'

export type PipelineStep = 'idle' | 'uploading' | 'parsing' | 'analyzing' | 'creating' | 'done' | 'error'

export interface DraftHU extends AIExtractedHU {
  _selected: boolean
  _created: boolean
  _error?: string
}

export const useTranscriptionsStore = defineStore('transcriptions', () => {
  const step = ref<PipelineStep>('idle')
  const error = ref<string | null>(null)
  const parsed = ref<ParsedTranscription | null>(null)
  const draftHUs = ref<DraftHU[]>([])
  const summary = ref<string>('')
  const selectedProjectId = ref<number | null>(null)

  const husCount = computed(() => draftHUs.value.length)
  const selectedHUs = computed(() => draftHUs.value.filter(h => h._selected))
  const hasDrafts = computed(() => draftHUs.value.length > 0)

  async function uploadAndParse(file: File) {
    step.value = 'parsing'
    error.value = null
    parsed.value = null
    draftHUs.value = []
    summary.value = ''

    try {
      const result = await parseFile(file)
      parsed.value = result
      step.value = 'idle'
      console.log(`[Alpha] File parsed: ${result.fileName}, ${result.text.length} chars`)
    } catch (e: any) {
      step.value = 'error'
      error.value = e.message
      console.error('[Alpha] Parse error:', e)
    }
  }

  async function runAnalysis(signal?: AbortSignal) {
    if (!parsed.value) {
      error.value = 'No hay transcripción para analizar'
      return
    }

    step.value = 'analyzing'
    error.value = null

    const store = useProjectsStore()
    const project = selectedProjectId.value
      ? store.projects.find(p => p.id === selectedProjectId.value)
      : null

    try {
      const result: AIAnalysisResult = await analyzeTranscription(
        parsed.value.text,
        project?.name,
        signal
      )
      draftHUs.value = result.hus.map(hu => ({
        ...hu,
        _selected: true,
        _created: false,
      }))
      summary.value = result.summary
      step.value = 'idle'
    } catch (e: any) {
      step.value = 'error'
      error.value = e.message
      console.error('[Alpha] AI analysis error:', e)
    }
  }

  async function createSelectedInKAPPA(): Promise<{ ok: number; fail: number }> {
    const projectId = selectedProjectId.value
    if (!projectId) {
      error.value = 'Seleccioná un proyecto'
      return { ok: 0, fail: 0 }
    }

    const toCreate = draftHUs.value.filter(h => h._selected && !h._created)
    if (toCreate.length === 0) return { ok: 0, fail: 0 }

    step.value = 'creating'
    error.value = null
    let ok = 0
    let fail = 0

    for (const hu of toCreate) {
      try {
        const result = await kappa.createUserStory({
          title: hu.title,
          description: hu.description + (hu.acceptance_criteria.length > 0
            ? `\n\n**Criterios de aceptación:**\n${hu.acceptance_criteria.map(c => `- ${c}`).join('\n')}`
            : ''),
          initiative: projectId,
          priority: hu.priority || 'Media',
          story_points: hu.story_points,
          status: 'todo',
        })
        hu._created = true
        hu._selected = false
        ok++

        await useWorkItemsStore().fetchWorkItems(projectId)
      } catch (e: any) {
        hu._error = e.message
        fail++
        console.error(`[Alpha] Failed to create HU "${hu.title}":`, e)
      }
    }

    step.value = 'idle'
    return { ok, fail }
  }

  function toggleHU(index: number) {
    if (draftHUs.value[index]) {
      draftHUs.value[index]._selected = !draftHUs.value[index]._selected
    }
  }

  function removeHU(index: number) {
    draftHUs.value.splice(index, 1)
  }

  function clearAll() {
    parsed.value = null
    draftHUs.value = []
    summary.value = ''
    step.value = 'idle'
    error.value = null
  }

  return {
    step,
    error,
    parsed,
    draftHUs,
    summary,
    selectedProjectId,
    husCount,
    selectedHUs,
    hasDrafts,
    uploadAndParse,
    runAnalysis,
    createSelectedInKAPPA,
    toggleHU,
    removeHU,
    clearAll,
  }
})
