<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">Verification Review</h2>
      <StatusBadge :status="batch?.status ?? 'PENDING_VERIFICATION'" />
    </div>

    <div v-if="batch?.rejectionReason" class="bg-red-50 border border-red-200 rounded-md p-4">
      <p class="text-sm font-medium text-red-800">Previous Rejection Reason:</p>
      <p class="text-sm text-red-700">{{ batch.rejectionReason }}</p>
    </div>

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

    <SeparationOfDutiesBanner
      v-model:blocked="sodBlocked"
      :entered-by-user-id="batch?.enteredByUserId"
      :current-user-id="auth.userId"
      :current-user-name="auth.userFullName"
    />

    <!-- Patient review -->
    <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 v-for="field in patientFields" :key="field.path">
          <div class="flex items-center gap-2">
            <input
              type="checkbox"
              :checked="fieldChecks[field.path]"
              @change="toggleCheck(field.path)"
              class="w-4 h-4 text-clinical-safe rounded"
            />
            <label class="text-xs text-gray-500">{{ field.label }}</label>
            <OcrConfidenceBadge
              :label="fieldConfidenceLabel(field.path)"
              :level="fieldConfidenceLevel(field.path)"
            />
          </div>
          <p
            class="text-sm mt-2 pl-8 font-medium"
            :class="fieldConfidenceClass(field.path)"
          >
            {{ field.value || '(empty)' }}
          </p>
        </div>
      </div>
    </fieldset>

    <!-- Allergies review (ALLERGY_UPDATE or MIXED) -->
    <fieldset v-if="allergyFields.length > 0" class="border border-gray-200 rounded-md p-4">
      <legend class="text-sm font-medium text-gray-700 px-2">Allergies</legend>
      <div class="space-y-3">
        <div v-for="field in allergyFields" :key="field.path">
          <div class="flex items-center gap-2">
            <input
              type="checkbox"
              :checked="fieldChecks[field.path]"
              @change="toggleCheck(field.path)"
              class="w-4 h-4 text-clinical-safe rounded"
            />
            <label class="text-xs text-gray-500">{{ field.label }}</label>
            <OcrConfidenceBadge
              :label="fieldConfidenceLabel(field.path)"
              :level="fieldConfidenceLevel(field.path)"
            />
          </div>
          <p
            class="text-sm mt-2 pl-8 font-medium"
            :class="fieldConfidenceClass(field.path)"
          >
            {{ field.value || '(empty)' }}
          </p>
        </div>
      </div>
    </fieldset>

    <!-- Medications review (MEDICATION_LIST or MIXED) -->
    <fieldset v-if="medicationFields.length > 0" class="border border-gray-200 rounded-md p-4">
      <legend class="text-sm font-medium text-gray-700 px-2">Medications</legend>
      <div class="space-y-3">
        <div v-for="field in medicationFields" :key="field.path">
          <div class="flex items-center gap-2">
            <input
              type="checkbox"
              :checked="fieldChecks[field.path]"
              @change="toggleCheck(field.path)"
              class="w-4 h-4 text-clinical-safe rounded"
            />
            <label class="text-xs text-gray-500">{{ field.label }}</label>
            <OcrConfidenceBadge
              :label="fieldConfidenceLabel(field.path)"
              :level="fieldConfidenceLevel(field.path)"
            />
          </div>
          <p
            class="text-sm mt-2 pl-8 font-medium"
            :class="fieldConfidenceClass(field.path)"
          >
            {{ field.value || '(empty)' }}
          </p>
        </div>
      </div>
    </fieldset>

    <!-- Encounter review -->
    <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 v-for="field in encounterFields" :key="field.path">
          <div class="flex items-center gap-2">
            <input
              type="checkbox"
              :checked="fieldChecks[field.path]"
              @change="toggleCheck(field.path)"
              class="w-4 h-4 text-clinical-safe rounded"
            />
            <label class="text-xs text-gray-500">{{ field.label }}</label>
            <OcrConfidenceBadge
              :label="fieldConfidenceLabel(field.path)"
              :level="fieldConfidenceLevel(field.path)"
            />
          </div>
          <p
            class="text-sm mt-2 pl-8 font-medium"
            :class="fieldConfidenceClass(field.path)"
          >
            {{ field.value || '(empty)' }}
          </p>
        </div>
      </div>
    </fieldset>

    <!-- Observations review -->
    <fieldset class="border border-gray-200 rounded-md p-4">
      <legend class="text-sm font-medium text-gray-700 px-2">
        Observations ({{ observations.length }})
      </legend>
      <div class="space-y-2">
        <ObservationRow
          v-for="(obs, index) in observations"
          :key="obs.id"
          :observation="obs"
          :readonly="true"
          :show-verified="true"
          :verified="fieldChecks[`observations[${index}].value`] ?? false"
          :value-input-class="observationValueConfidenceClass(obs.observationCode)"
          :ocr-label="fieldConfidenceLabel(`observation.${obs.observationCode}.value`)"
          :ocr-level="fieldConfidenceLevel(`observation.${obs.observationCode}.value`)"
          @verify="(_obsId, passed) => toggleCheck(`observations[${index}].value`, passed)"
        />
      </div>
    </fieldset>

    <!-- Verification progress -->
    <div class="bg-gray-50 rounded-md p-4">
      <div class="flex items-center justify-between text-sm">
        <span>Fields verified:</span>
        <span :class="allChecked ? 'text-clinical-safe font-bold' : 'text-gray-600'">
          {{ checkedCount }} / {{ totalFields }}
        </span>
      </div>
      <div class="w-full bg-gray-200 rounded-full h-2 mt-2">
        <div
          class="bg-clinical-safe h-2 rounded-full transition-all"
          :style="{ width: `${(checkedCount / Math.max(totalFields, 1)) * 100}%` }"
        />
      </div>
    </div>

    <!-- Actions -->
    <div class="flex flex-col sm:flex-row gap-4 pt-4 border-t">
      <button
        @click="approveVerification"
        class="btn-primary"
        :disabled="!allChecked || processing || sodBlocked"
      >
        {{ processing ? 'Processing...' : 'Approve - Verified' }}
      </button>
      <button
        @click="showRejectDialog = true"
        class="btn-danger"
        :disabled="processing || sodBlocked"
      >
        Reject
      </button>
    </div>

    <ConfirmDialog
      :open="showRejectDialog"
      title="Reject Batch"
      body="This returns the batch for rework. A reason is required."
      confirm-label="Confirm Rejection"
      variant="danger"
      :confirm-disabled="!rejectionReason.trim() || processing"
      @confirm="rejectVerification"
      @cancel="showRejectDialog = false"
    >
      <textarea
        v-model="rejectionReason"
        class="form-input"
        rows="4"
        placeholder="Reason for rejection (required)..."
      />
    </ConfirmDialog>

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

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
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 SeparationOfDutiesBanner from '../components/SeparationOfDutiesBanner.vue'
import ConfirmDialog from '../components/ConfirmDialog.vue'
import type { BatchDetailResponse, DraftObservation } from '../types'

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

const auth = useAuthStore()
const batchStore = useBatchStore()
const router = useRouter()
const toast = useToast()
const processing = ref(false)
const errorMessage = ref('')
const showRejectDialog = ref(false)
const rejectionReason = ref('')
const sodBlocked = ref(false)

const fieldChecks = ref<Record<string, boolean>>({})
const observations = ref<DraftObservation[]>([])

interface FieldInfo {
  path: string
  label: string
  value: string
}

const patientFields = ref<FieldInfo[]>([])
const allergyFields = ref<FieldInfo[]>([])
const medicationFields = ref<FieldInfo[]>([])
const encounterFields = ref<FieldInfo[]>([])

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)

watch(
  () => batchStore.currentDraft,
  (draft) => {
    if (!draft) return

    observations.value = draft.observations ?? []

    // Build patient field list
    if (draft.patient) {
      patientFields.value = [
        { path: 'patient.fullName', label: 'Full Name', value: draft.patient.fullName ?? '' },
        { path: 'patient.dateOfBirth', label: 'Date of Birth', value: draft.patient.dateOfBirth ?? '' },
        { path: 'patient.sex', label: 'Sex', value: draft.patient.sex ?? '' },
        { path: 'patient.bloodType', label: 'Blood Type', value: draft.patient.bloodType ?? '' },
        { path: 'patient.emergencyContact', label: 'Emergency Contact', value: draft.patient.emergencyContact ?? '' },
      ]

      // Build allergy fields
      allergyFields.value = []
      if (showAllergies.value) {
        if (draft.patient.noKnownAllergies) {
          allergyFields.value = [
            { path: 'patient.noKnownAllergies', label: 'No Known Allergies', value: 'Yes (NKA)' },
          ]
        } else {
          const items = draft.patient.allergies ?? []
          allergyFields.value = items.map((item, i) => ({
            path: `patient.allergies[${i}]`,
            label: `Allergy ${i + 1}`,
            value: item,
          }))
          if (items.length === 0) {
            allergyFields.value = [
              { path: 'patient.allergies', label: 'Allergies', value: '(none entered)' },
            ]
          }
        }
      }

      // Build medication fields
      medicationFields.value = []
      if (showMedications.value) {
        if (draft.patient.noActiveMedications) {
          medicationFields.value = [
            { path: 'patient.noActiveMedications', label: 'No Active Medications', value: 'Yes' },
          ]
        } else {
          const items = draft.patient.medications ?? []
          medicationFields.value = items.map((item, i) => ({
            path: `patient.medications[${i}]`,
            label: `Medication ${i + 1}`,
            value: item,
          }))
          if (items.length === 0) {
            medicationFields.value = [
              { path: 'patient.medications', label: 'Medications', value: '(none entered)' },
            ]
          }
        }
      }
    }

    // Build encounter field list
    if (draft.encounter) {
      encounterFields.value = [
        { path: 'encounter.admissionDate', label: 'Admission Date', value: draft.encounter.admissionDate ?? '' },
        { path: 'encounter.department', label: 'Department', value: draft.encounter.department ?? '' },
        { path: 'encounter.roomBed', label: 'Room / Bed', value: draft.encounter.roomBed ?? '' },
        { path: 'encounter.admissionReason', label: 'Admission Reason', value: draft.encounter.admissionReason ?? '' },
      ]
      if (showEncounterSummary.value) {
        encounterFields.value.push(
          { path: 'encounter.status', label: 'Encounter Status', value: draft.encounter.status ?? '' },
          { path: 'encounter.dischargeDiagnosis', label: 'Discharge Diagnosis', value: draft.encounter.dischargeDiagnosis ?? '' },
        )
      }
    }

    // Initialize all checks to false
    fieldChecks.value = {}
    patientFields.value.forEach((f) => { fieldChecks.value[f.path] = false })
    allergyFields.value.forEach((f) => { fieldChecks.value[f.path] = false })
    medicationFields.value.forEach((f) => { fieldChecks.value[f.path] = false })
    encounterFields.value.forEach((f) => { fieldChecks.value[f.path] = false })
    observations.value.forEach((_, i) => { fieldChecks.value[`observations[${i}].value`] = false })
  },
  { immediate: true }
)

const totalFields = computed(
  () => patientFields.value.length + allergyFields.value.length + medicationFields.value.length
       + encounterFields.value.length + observations.value.length
)
const checkedCount = computed(
  () => Object.values(fieldChecks.value).filter(Boolean).length
)
const allChecked = computed(() => checkedCount.value === totalFields.value && totalFields.value > 0)

function toggleCheck(path: string, value?: boolean) {
  fieldChecks.value[path] = value ?? !fieldChecks.value[path]
}

async function approveVerification() {
  if (sodBlocked.value) return
  processing.value = true
  errorMessage.value = ''
  try {
    const checks = Object.entries(fieldChecks.value).map(([fieldPath, passed]) => ({
      fieldPath,
      passed,
    }))
    await batchStore.verifyBatch(props.batchId, checks, true)
    toast.success('Batch verified successfully')
    router.push('/verification')
  } catch (e: unknown) {
    const msg = e instanceof Error ? e.message : 'Verification failed'
    errorMessage.value = msg
    toast.error(msg)
  } finally {
    processing.value = false
  }
}

async function rejectVerification() {
  processing.value = true
  errorMessage.value = ''
  try {
    await batchStore.rejectBatch(props.batchId, rejectionReason.value)
    showRejectDialog.value = false
    toast.warning('Batch rejected')
    router.push('/verification')
  } catch (e: unknown) {
    const msg = e instanceof Error ? e.message : 'Rejection failed'
    errorMessage.value = msg
    toast.error(msg)
  } finally {
    processing.value = false
  }
}
</script>