<template>
  <div
    :class="[
      'ivyforms-field',
      'ivyforms-field__slider',
      'ivyforms-field__slider_' + field.id,
      field.cssClasses,
      { 'is-readonly': field.readOnly },
      {
        'ivyforms-field__slider--grid-and-desc': !!(field.showGrid && field.description),
      },
    ]"
  >
    <IvyFormItem
      :label="field.hideLabel ? '' : field.label"
      :required="field.required"
      :error="error"
      :prop="field.type + '_' + field.fieldIndex"
      :show-info="!!field.description"
      :info-text="field.description || ''"
      :show-info-icon="false"
      :label-position="field.labelPosition"
    >
      <IvySlider
        :id="fieldID"
        v-model="localModelValue"
        :min="field.minValue ?? 0"
        :max="field.maxValue ?? 100"
        :step="field.step ?? 1"
        :disabled="disabled"
        :readonly="field.readOnly"
        :show-input="false"
        :show-labels="true"
        :show-grid="field.showGrid || false"
        :show-tooltip="true"
        :aria-label="field.label"
      />
    </IvyFormItem>
  </div>
</template>

<script setup lang="ts">
import { computed, inject } from 'vue'
import IvyFormItem from '@/views/_components/form/IvyFormItem.vue'
import IvySlider from '@/views/_components/slider/IvySlider.vue'
import type { Field } from '@/types/field'

interface FieldProps {
  modelValue: string | number | null | undefined
  field: Field
  disabled?: boolean
  error?: string
}

const props = withDefaults(defineProps<FieldProps>(), {
  modelValue: '',
  disabled: false,
  error: '',
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: number | null): void
}>()

// Inject clearFieldError function from parent
const clearFieldError = inject<(fieldKey: string) => void>('clearFieldError', () => {})

// Generate field key for clearing errors
const fieldKey = computed(() => {
  return props.field.type + '_' + props.field.fieldIndex
})

// Generate field ID for DOM
const fieldID = computed(() => {
  return `ivyforms-field__slider_${props.field.formId || ''}_${props.field.fieldIndex || ''}`
})

// Local model value for v-model binding
const localModelValue = computed({
  get(): number {
    const value = props.modelValue
    // Convert to number and ensure it's within min/max range
    if (value === null || value === undefined || value === '') {
      const defaultVal =
        props.field.defaultValue !== undefined &&
        props.field.defaultValue !== null &&
        props.field.defaultValue !== ''
          ? Number(props.field.defaultValue)
          : (props.field.minValue ?? 0)
      return defaultVal
    }
    const num = Number(value)
    const min = props.field.minValue ?? 0
    const max = props.field.maxValue ?? 100
    return Math.max(min, Math.min(max, num))
  },
  set(newValue: number) {
    // Clear any previous errors when user modifies the field
    clearFieldError(fieldKey.value)

    // Emit the new value
    emit('update:modelValue', newValue)
  },
})
</script>

<style lang="scss" scoped>
.ivyforms-field__slider {
  width: 100%;
  padding: var(--Spacing-md, 16px) 0;
}

/* Grid ticks + description: default form content gap is tight for tall caps */
.ivyforms-field__slider--grid-and-desc {
  :deep(.el-form-item__content) {
    gap: var(--Spacing-sm, 12px);
  }
}
</style>
