import { computed, reactive, ref } from 'vue'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:8000'

export interface QuestionOption {
  value: string
  label: string
  icon?: string
}

export interface Question {
  code: string
  type: string
  title: string
  options?: QuestionOption[]
  min?: number
  max?: number
}

export interface MtsPreparation {
  session_id: string
  proposed_presenting_flowchart?: string | null
  red_flag_indicators: string[]
  suggested_priority_level?: string | null
}

const language = ref<'de' | 'en' | 'ar'>('de')
const questions = reactive<Question[]>([])
const isLoadingConfig = ref(false)
const loadError = ref<string | null>(null)

const chiefComplaint = ref<string | null>(null)
const pain = ref<number>(0)

const isSubmitting = ref(false)
const submitError = ref<string | null>(null)
const result = ref<MtsPreparation | null>(null)

const chiefComplaintQuestion = computed(() =>
  questions.find((q) => q.code === 'chief_complaint') ?? null,
)

const painQuestion = computed(() => questions.find((q) => q.code === 'pain_intensity') ?? null)

const priorityClass = computed(() => {
  const level = result.value?.suggested_priority_level
  if (!level) return ''
  if (level === 'RED_OR_ORANGE') return 'priority-high'
  return 'priority-default'
})

const priorityLabel = computed(() => {
  const level = result.value?.suggested_priority_level
  if (!level) return ''
  if (level === 'RED_OR_ORANGE') return 'Hohe Dringlichkeit'
  return 'Priorität'
})

async function loadQuestions() {
  isLoadingConfig.value = true
  loadError.value = null
  questions.splice(0, questions.length)
  chiefComplaint.value = null
  pain.value = 0
  result.value = null

  try {
    const res = await fetch(`${API_BASE_URL}/questions/${language.value}`)
    if (!res.ok) {
      throw new Error(`HTTP ${res.status}`)
    }
    const data = (await res.json()) as { language: string; questions: Question[] }
    questions.push(...data.questions)
  } catch (err) {
    console.error('Failed to load questions', err)
    loadError.value = 'Konfiguration konnte nicht geladen werden. Bitte prüfen, ob der Server läuft.'
  } finally {
    isLoadingConfig.value = false
  }
}

async function startSession() {
  if (!chiefComplaint.value) return

  isSubmitting.value = true
  submitError.value = null
  result.value = null

  const payload = {
    language: language.value,
    answers: [
      { question_code: 'chief_complaint', value: chiefComplaint.value },
      { question_code: 'pain_intensity', value: pain.value },
    ],
  }

  try {
    const res = await fetch(`${API_BASE_URL}/sessions`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    })

    if (!res.ok) {
      throw new Error(`HTTP ${res.status}`)
    }

    result.value = (await res.json()) as MtsPreparation
  } catch (err) {
    console.error('Failed to start session', err)
    submitError.value = 'Sitzung konnte nicht angelegt werden.'
  } finally {
    isSubmitting.value = false
  }
}

export function useTriageSession() {
  return {
    language,
    questions,
    isLoadingConfig,
    loadError,
    chiefComplaint,
    pain,
    isSubmitting,
    submitError,
    result,
    chiefComplaintQuestion,
    painQuestion,
    priorityClass,
    priorityLabel,
    loadQuestions,
    startSession,
  }
}
