<template>
  <div class="h-full overflow-y-auto p-4 space-y-6">
    <div class="flex items-center justify-between">
      <h2 class="text-lg font-semibold">Data Entry</h2>
      <StatusBadge :status="batch?.status" />
    </div>

    <div v-if="ocrConfidence" class="ocr-banner">
      Pre-filled by OCR ({{ ocrConfidence.provider }}) — review against the scan.
      OCR is assistive, not authoritative.
    </div>

    <!-- Patient section -->
    <fieldset class="border border-gray-200 rounded-md p-4">
      <legend class="text-sm font-medium text-gray-700 px-2">Patient Demographics</legend>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label class="flex items-center gap-2 text-xs text-gray-500">
            Full Name
            <OcrConfidenceBadge :label="fieldConfidenceLabel('patient.fullName')" :level="fieldConfidenceLevel('patient.fullName')" />
          </label>
          <input
            v-model="patient.fullName"
            @blur="savePatient"
            type="text"
            :class="['form-input', 'text-sm', fieldConfidenceClass('patient.fullName')]"
          />
        </div>
        <div>
          <label class="flex items-center gap-2 text-xs text-gray-500">
            Date of Birth
            <OcrConfidenceBadge :label="fieldConfidenceLabel('patient.dateOfBirth')" :level="fieldConfidenceLevel('patient.dateOfBirth')" />
          </label>
          <input
            v-model="patient.dateOfBirth"
            @blur="savePatient"
            type="date"
            :class="['form-input', 'text-sm', fieldConfidenceClass('patient.dateOfBirth')]"
          />
        </div>
        <div>
          <label class="flex items-center gap-2 text-xs text-gray-500">
            Sex
            <OcrConfidenceBadge :label="fieldConfidenceLabel('patient.sex')" :level="fieldConfidenceLevel('patient.sex')" />
          </label>
          <select
            v-model="patient.sex"
            @change="savePatient"
            :class="['form-input', 'text-sm', fieldConfidenceClass('patient.sex')]"
          >
            <option value="">Select...</option>
            <option value="male">Male</option>
            <option value="female">Female</option>
            <option value="other">Other</option>
          </select>
        </div>
        <div>
          <label class="block text-xs text-gray-500">Blood Type</label>
          <select v-model="patient.bloodType" @change="savePatient" class="form-input text-sm">
            <option value="">Unknown</option>
            <option v-for="bt in bloodTypes" :key="bt" :value="bt">{{ bt }}</option>
          </select>
        </div>
        <div class="col-span-2">
          <label class="block text-xs text-gray-500">Emergency Contact</label>
          <input
            v-model="patient.emergencyContact"
            @blur="savePatient"
            type="text"
            class="form-input text-sm"
          />
        </div>
      </div>
    </fieldset>

    <!-- Allergies section (ALLERGY_UPDATE or MIXED) -->
    <fieldset v-if="showAllergies" class="border border-gray-200 rounded-md p-4">
      <legend class="text-sm font-medium text-gray-700 px-2">Allergies</legend>
      <label class="flex items-center gap-2 mb-3 cursor-pointer">
        <input
          v-model="patient.noKnownAllergies"
          @change="onNoKnownAllergiesChange"
          type="checkbox"
          class="w-4 h-4 text-clinical-safe rounded"
        />
        <span class="text-sm">No known allergies (NKA)</span>
      </label>
      <div v-if="!patient.noKnownAllergies" class="space-y-2">
        <div
          v-for="(_allergy, idx) in allergies"
          :key="idx"
          class="flex items-center gap-2"
        >
          <input
            v-model="allergies[idx]"
            @blur="saveAllergies"
            type="text"
            class="form-input text-sm flex-1"
            placeholder="Allergy (e.g. Penicillin)"
          />
          <button
            @click="removeAllergy(idx)"
            class="text-clinical-danger hover:text-red-800 text-sm"
          >
            Remove
          </button>
        </div>
        <button @click="addAllergy" class="text-sm text-primary-600 hover:text-primary-800">
          + Add Allergy
        </button>
      </div>
    </fieldset>

    <!-- Medications section (MEDICATION_LIST or MIXED) -->
    <fieldset v-if="showMedications" class="border border-gray-200 rounded-md p-4">
      <legend class="text-sm font-medium text-gray-700 px-2">Medications</legend>
      <label class="flex items-center gap-2 mb-3 cursor-pointer">
        <input
          v-model="patient.noActiveMedications"
          @change="onNoActiveMedicationsChange"
          type="checkbox"
          class="w-4 h-4 text-clinical-safe rounded"
        />
        <span class="text-sm">No active medications</span>
      </label>
      <div v-if="!patient.noActiveMedications" class="space-y-2">
        <div
          v-for="(_med, idx) in medications"
          :key="idx"
          class="flex items-center gap-2"
        >
          <input
            v-model="medications[idx]"
            @blur="saveMedications"
            type="text"
            class="form-input text-sm flex-1"
            placeholder="Medication (e.g. Metoprolol 50mg BID)"
          />
          <button
            @click="removeMedication(idx)"
            class="text-clinical-danger hover:text-red-800 text-sm"
          >
            Remove
          </button>
        </div>
        <button @click="addMedication" class="text-sm text-primary-600 hover:text-primary-800">
          + Add Medication
        </button>
      </div>
    </fieldset>

    <!-- Encounter section -->
    <fieldset class="border border-gray-200 rounded-md p-4">
      <legend class="text-sm font-medium text-gray-700 px-2">Encounter Context</legend>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label class="flex items-center gap-2 text-xs text-gray-500">
            Admission Date
            <OcrConfidenceBadge :label="fieldConfidenceLabel('encounter.admissionDate')" :level="fieldConfidenceLevel('encounter.admissionDate')" />
          </label>
          <input
            v-model="encounter.admissionDate"
            @blur="saveEncounter"
            type="datetime-local"
            :class="['form-input', 'text-sm', fieldConfidenceClass('encounter.admissionDate')]"
          />
        </div>
        <div>
          <label class="flex items-center gap-2 text-xs text-gray-500">
            Department
            <OcrConfidenceBadge :label="fieldConfidenceLabel('encounter.department')" :level="fieldConfidenceLevel('encounter.department')" />
          </label>
          <select
            v-model="encounter.department"
            @change="saveEncounter"
            :class="['form-input', 'text-sm', fieldConfidenceClass('encounter.department')]"
          >
            <option value="">—</option>
            <option v-for="dept in departments" :key="dept" :value="dept">{{ dept }}</option>
          </select>
        </div>
        <div>
          <label class="flex items-center gap-2 text-xs text-gray-500">
            Room / Bed
            <OcrConfidenceBadge :label="fieldConfidenceLabel('encounter.roomBed')" :level="fieldConfidenceLevel('encounter.roomBed')" />
          </label>
          <input
            v-model="encounter.roomBed"
            @blur="saveEncounter"
            type="text"
            :class="['form-input', 'text-sm', fieldConfidenceClass('encounter.roomBed')]"
          />
        </div>
        <div>
          <label class="flex items-center gap-2 text-xs text-gray-500">
            Admission Reason
            <OcrConfidenceBadge :label="fieldConfidenceLabel('encounter.admissionReason')" :level="fieldConfidenceLevel('encounter.admissionReason')" />
          </label>
          <input
            v-model="encounter.admissionReason"
            @blur="saveEncounter"
            type="text"
            :class="['form-input', 'text-sm', fieldConfidenceClass('encounter.admissionReason')]"
          />
        </div>
        <div v-if="showEncounterSummary">
          <label class="block text-xs text-gray-500">Encounter Status</label>
          <select v-model="encounter.status" @change="saveEncounter" class="form-input text-sm">
            <option value="">—</option>
            <option value="active">Active</option>
            <option value="discharged">Discharged</option>
          </select>
        </div>
        <div v-if="showEncounterSummary" class="col-span-2">
          <label class="block text-xs text-gray-500">Discharge Diagnosis</label>
          <textarea
            v-model="encounter.dischargeDiagnosis"
            @blur="saveEncounter"
            class="form-input text-sm"
            rows="2"
            placeholder="Discharge diagnosis..."
          />
        </div>
      </div>
    </fieldset>

    <!-- Observations section -->
    <fieldset class="border border-gray-200 rounded-md p-4">
      <legend class="text-sm font-medium text-gray-700 px-2">Observations</legend>
      <div class="space-y-2">
        <ObservationRow
          v-for="obs in observations"
          :key="obs.id"
          :observation="obs"
          :value-input-class="observationValueConfidenceClass(obs.observationCode)"
          :ocr-label="fieldConfidenceLabel(`observation.${obs.observationCode}.value`)"
          :ocr-level="fieldConfidenceLevel(`observation.${obs.observationCode}.value`)"
          @update="(field, value) => handleObsUpdate(obs.id, field, value)"
          @delete="handleObsDelete"
        />
        <button @click="addObservation" class="btn-primary text-sm">
          + Add Observation
        </button>
      </div>
    </fieldset>

    <!-- Submit -->
    <div class="flex flex-col sm:flex-row gap-4 pt-4 border-t">
      <button
        @click="submitForVerification"
        class="btn-primary"
        :disabled="submitting"
      >
        {{ submitting ? 'Submitting...' : 'Submit for Verification' }}
      </button>
    </div>

    <div v-if="errorMessage" class="text-clinical-danger text-sm">
      {{ errorMessage }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { useBatchStore } from '../stores/batches'
import { useToast } from '../composables/useToast'
import { useOcrFieldConfidence } from '../composables/useOcrFieldConfidence'
import ObservationRow from '../components/ObservationRow.vue'
import StatusBadge from '../components/StatusBadge.vue'
import OcrConfidenceBadge from '../components/OcrConfidenceBadge.vue'
import type { BatchDetailResponse, DraftObservation } from '../types'

const props = defineProps<{
  batch: BatchDetailResponse | null
  batchId: string
}>()

const batchStore = useBatchStore()
const toast = useToast()
const submitting = ref(false)
const errorMessage = ref('')

const bloodTypes = ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-']
const departments = [
  'Emergency Department',
  'Internal Medicine',
  'General Medicine',
  'Surgery',
  'ICU',
  'NICU',
  'Medical-Surgical',
  'Outpatient Clinic',
  'Pediatrics',
  'Obstetrics & Gynecology',
  'Labor & Delivery',
  'Cardiology',
  'Orthopedics',
  'Neurology',
  'Oncology',
  'Radiology',
  'Laboratory',
  'Psychiatry',
  'Physical Therapy',
  'Anesthesiology',
]

const fieldReqs = computed(() => batchStore.currentDraft?.fieldRequirements)
const ocrConfidence = computed(() => batchStore.currentDraft?.ocrConfidence ?? null)
const {
  fieldConfidenceClass,
  fieldConfidenceLabel,
  fieldConfidenceLevel,
} = useOcrFieldConfidence(ocrConfidence)

function observationValueConfidenceClass(observationCode: string): string {
  if (!observationCode) return ''
  return fieldConfidenceClass(`observation.${observationCode}.value`)
}

const showAllergies = computed(() => fieldReqs.value?.showAllergies ?? false)
const showMedications = computed(() => fieldReqs.value?.showMedications ?? false)
const showEncounterSummary = computed(() => fieldReqs.value?.showEncounterSummaryFields ?? false)

const patient = reactive({
  fullName: '',
  dateOfBirth: '',
  sex: '',
  bloodType: '',
  emergencyContact: '',
  noKnownAllergies: false,
  noActiveMedications: false,
})

const allergies = ref<string[]>([])
const medications = ref<string[]>([])

const encounter = reactive({
  admissionDate: '',
  department: '',
  roomBed: '',
  admissionReason: '',
  dischargeDiagnosis: '',
  status: '',
})

const observations = ref<DraftObservation[]>([])

// Load draft data when batch changes
watch(
  () => batchStore.currentDraft,
  (draft) => {
    if (!draft) return
    if (draft.patient) {
      Object.assign(patient, {
        fullName: draft.patient.fullName ?? '',
        dateOfBirth: draft.patient.dateOfBirth ?? '',
        sex: draft.patient.sex ?? '',
        bloodType: draft.patient.bloodType ?? '',
        emergencyContact: draft.patient.emergencyContact ?? '',
        noKnownAllergies: draft.patient.noKnownAllergies ?? false,
        noActiveMedications: draft.patient.noActiveMedications ?? false,
      })
      allergies.value = draft.patient.allergies ?? []
      medications.value = draft.patient.medications ?? []
    }
    if (draft.encounter) {
      Object.assign(encounter, {
        admissionDate: draft.encounter.admissionDate?.substring(0, 16) ?? '',
        department: draft.encounter.department ?? '',
        roomBed: draft.encounter.roomBed ?? '',
        admissionReason: draft.encounter.admissionReason ?? '',
        dischargeDiagnosis: draft.encounter.dischargeDiagnosis ?? '',
        status: draft.encounter.status ?? '',
      })
    }
    observations.value = draft.observations ?? []
  },
  { immediate: true }
)

function addAllergy() {
  allergies.value.push('')
}

function removeAllergy(idx: number) {
  allergies.value.splice(idx, 1)
  saveAllergies()
}

async function saveAllergies() {
  try {
    await batchStore.saveDraftPatient(props.batchId, {
      ...patient,
      allergies: allergies.value.filter(a => a.trim()),
    })
    toast.success('Allergies saved')
  } catch (e: unknown) {
    const msg = e instanceof Error ? e.message : 'Failed to save allergies'
    errorMessage.value = msg
    toast.error(msg)
  }
}

function onNoKnownAllergiesChange() {
  if (patient.noKnownAllergies) {
    allergies.value = []
  }
  savePatient()
}

function addMedication() {
  medications.value.push('')
}

function removeMedication(idx: number) {
  medications.value.splice(idx, 1)
  saveMedications()
}

async function saveMedications() {
  try {
    await batchStore.saveDraftPatient(props.batchId, {
      ...patient,
      medications: medications.value.filter(m => m.trim()),
    })
    toast.success('Medications saved')
  } catch (e: unknown) {
    const msg = e instanceof Error ? e.message : 'Failed to save medications'
    errorMessage.value = msg
    toast.error(msg)
  }
}

function onNoActiveMedicationsChange() {
  if (patient.noActiveMedications) {
    medications.value = []
  }
  savePatient()
}

async function savePatient() {
  try {
    await batchStore.saveDraftPatient(props.batchId, {
      ...patient,
      allergies: patient.noKnownAllergies ? null : allergies.value.filter(a => a.trim()),
      medications: patient.noActiveMedications ? null : medications.value.filter(m => m.trim()),
    })
    toast.success('Patient demographics saved')
  } catch (e: unknown) {
    const msg = e instanceof Error ? e.message : 'Failed to save patient'
    errorMessage.value = msg
    toast.error(msg)
  }
}

async function saveEncounter() {
  try {
    await batchStore.saveDraftEncounter(props.batchId, encounter)
    toast.success('Encounter context saved')
  } catch (e: unknown) {
    const msg = e instanceof Error ? e.message : 'Failed to save encounter'
    errorMessage.value = msg
    toast.error(msg)
  }
}

async function addObservation() {
  await batchStore.addObservation(props.batchId, {
    observationCode: '',
    value: 0,
    unit: '',
    recordedAt: new Date().toISOString(),
    note: null,
  })
  observations.value = batchStore.currentDraft?.observations ?? []
}

async function handleObsUpdate(obsId: string, field: string, value: unknown) {
  const obs = observations.value.find((o) => o.id === obsId)
  if (!obs) return
  ;(obs as Record<string, unknown>)[field] = value
  await batchStore.updateObservation(props.batchId, obsId, obs)
}

async function handleObsDelete(obsId: string) {
  await batchStore.deleteObservation(props.batchId, obsId)
  observations.value = batchStore.currentDraft?.observations ?? []
}

async function submitForVerification() {
  submitting.value = true
  errorMessage.value = ''
  try {
    await batchStore.submitForVerification(props.batchId)
    toast.success('Batch submitted for verification')
  } catch (e: unknown) {
    const msg = e instanceof Error ? e.message : 'Submit failed'
    errorMessage.value = msg
    toast.error(msg)
  } finally {
    submitting.value = false
  }
}
</script>