<script setup>
import { reactive, computed, watch } from 'vue'
import Modal from '@/components/ui/Modal.vue'
import Button from '@/components/ui/Button.vue'
import {
  emptyThresholdForm,
  validateThresholdForm,
} from '@/composables/thresholdForm'

const props = defineProps({
  open: { type: Boolean, default: false },
  title: { type: String, default: 'Edit Threshold' },
  initialValues: { type: Object, default: () => emptyThresholdForm() },
  submitting: { type: Boolean, default: false },
  error: { type: String, default: '' },
  readOnlyCode: { type: Boolean, default: false },
})

const emit = defineEmits(['close', 'submit'])

const values = reactive(emptyThresholdForm())
const touched = reactive(emptyThresholdForm())

const validation = computed(() => validateThresholdForm(values))
const fieldErrors = computed(() => validation.value.errors)

const fields = [
  { key: 'observationCode', label: 'Observation code', type: 'text' },
  { key: 'displayName', label: 'Display name', type: 'text' },
  { key: 'unit', label: 'Unit', type: 'text' },
  { key: 'criticalLow', label: 'Critical low', type: 'number', step: '0.001' },
  { key: 'warningLow', label: 'Warning low', type: 'number', step: '0.001' },
  { key: 'warningHigh', label: 'Warning high', type: 'number', step: '0.001' },
  { key: 'criticalHigh', label: 'Critical high', type: 'number', step: '0.001' },
]

watch(() => props.open, (isOpen) => {
  if (!isOpen) return
  Object.assign(values, props.initialValues)
  for (const field of fields) touched[field.key] = false
}, { immediate: true })

function onBlur(key) {
  touched[key] = true
}

function showError(key) {
  return Boolean(touched[key] && fieldErrors.value[key])
}

function submit() {
  for (const field of fields) touched[field.key] = true
  if (!validation.value.valid) return
  emit('submit', validation.value.payload)
}
</script>

<template>
  <Modal :open="open" :title="title" @close="emit('close')">
    <form class="space-y-4" @submit.prevent="submit">
      <div v-for="field in fields" :key="field.key">
        <label class="mb-2 block text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400">
          {{ field.label }}
        </label>
        <input
          v-model="values[field.key]"
          :type="field.type"
          :step="field.step"
          :readonly="readOnlyCode && field.key === 'observationCode'"
          class="w-full rounded border px-4 py-2 text-sm focus-visible:ring-2 focus-visible:ring-blue-500 dark:border-gray-600 dark:bg-gray-800 dark:text-white"
          :class="[
            showError(field.key) ? 'border-red-500' : 'border-gray-300',
            readOnlyCode && field.key === 'observationCode' ? 'bg-gray-100 dark:bg-gray-700' : '',
          ]"
          @blur="onBlur(field.key)"
        >
        <p v-if="showError(field.key)" class="mt-1 text-xs text-red-600 dark:text-red-400">
          {{ fieldErrors[field.key] }}
        </p>
      </div>

      <p v-if="error" class="text-sm text-red-600 dark:text-red-400">{{ error }}</p>

      <div class="flex justify-end gap-2">
        <Button type="button" variant="ghost" @click="emit('close')">Cancel</Button>
        <Button type="submit" :disabled="submitting">
          {{ submitting ? 'Saving…' : 'Save' }}
        </Button>
      </div>
    </form>
  </Modal>
</template>
