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 answers = reactive<Record<string, string | number | boolean | null>>({
  chief_complaint: null,
  breathlessness: null,
  pain_intensity: 0,
})

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

const orderedQuestions = computed(() => questions)
const chiefComplaintQuestion = computed(() => questions.find((q) => q.code === 'chief_complaint') ?? null)
const flowQuestions = computed(() => questions.filter((q) => q.code !== 'chief_complaint' && q.code !== 'pain_intensity'))
const painQuestion = computed(() => questions.find((q) => q.code === 'pain_intensity') ?? null)
const chiefComplaint = computed({
  get: () => (typeof answers.chief_complaint === 'string' ? answers.chief_complaint : null),
  set: (value: string | null) => {
    answers.chief_complaint = value
  },
})
const pain = computed({
  get: () => (typeof answers.pain_intensity === 'number' ? answers.pain_intensity : 0),
  set: (value: number) => {
    answers.pain_intensity = value
  },
})

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

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

function resetAnswers() {
  answers.chief_complaint = null
  answers.breathlessness = null
  answers.pain_intensity = 0
}

function setAnswer(questionCode: string, value: string | number | boolean | null) {
  answers[questionCode] = value
}

function getAnswer(questionCode: string) {
  return answers[questionCode] ?? null
}

async function loadQuestions() {
  isLoadingConfig.value = true
  loadError.value = null
  questions.splice(0, questions.length)
  resetAnswers()
  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: orderedQuestions.value
      .filter((q) => answers[q.code] !== null && answers[q.code] !== undefined)
      .map((q) => ({ question_code: q.code, value: answers[q.code] })),
  }

  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,
    orderedQuestions,
    isLoadingConfig,
    loadError,
    answers,
    chiefComplaint,
    pain,
    flowQuestions,
    isSubmitting,
    submitError,
    result,
    chiefComplaintQuestion,
    painQuestion,
    priorityClass,
    priorityLabel,
    setAnswer,
    getAnswer,
    loadQuestions,
    startSession,
    resetAnswers,
  }
}
