<template>
  <div :class="wrapperClasses">
    <div class="relative">
      <input
        :id="inputId"
        v-model="modelValue"
        type="date"
        :name="name"
        :disabled="disabled"
        :readonly="readonly"
        :required="required"
        :min="min"
        :max="max"
        :class="inputClasses"
        :aria-invalid="hasError"
        :aria-describedby="hasError ? `${inputId}-error` : undefined"
        @focus="handleFocus"
        @blur="handleBlur"
        @input="handleInput"
        @change="handleChange"
      />

      <!-- Calendar icon -->
      <div
        v-if="!disabled"
        class="absolute right-0 top-1/2 transform -translate-y-1/2 pointer-events-none"
      >
        <svg
          class="w-5 h-5 text-gray-400"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
          />
        </svg>
      </div>

      <label
        v-if="hasFloatingLabel"
        :for="inputId"
        :class="floatingLabelClasses"
      >
        {{ label }}<span v-if="required" class="text-red-500 ml-1">*</span>
      </label>
    </div>

    <Transition name="error-fade">
      <div
        v-if="hasError && errorMessage"
        :id="`${inputId}-error`"
        class="mt-1 text-sm text-red-600"
        role="alert"
        aria-live="polite"
      >
        {{ errorMessage }}
      </div>
    </Transition>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, useId } from 'vue'
import type { DatePickerProps, DatePickerEmits } from '@/types/components'

const props = withDefaults(defineProps<DatePickerProps>(), {
  disabled: false,
  readonly: false,
  required: false,
  error: false,
  size: 'md',
  variant: 'default'
})

const emit = defineEmits<DatePickerEmits>()

// Generate unique ID for the input
const inputId = useId()

// Reactive state
const isFocused = ref(false)
const hasValue = computed(() => props.modelValue != null && props.modelValue !== '')
const hasError = computed(() => props.error || !!props.errorMessage)
const hasFloatingLabel = computed(() => !!props.label)
const shouldHidePlaceholder = computed(() => !hasValue.value && !isFocused.value)

// Handle v-model updates
const modelValue = computed({
  get: () => props.modelValue || '',
  set: (value) => emit('update:modelValue', value)
})

// Event handlers
const handleFocus = (event: FocusEvent) => {
  isFocused.value = true
  emit('focus', event)
}

const handleBlur = (event: FocusEvent) => {
  isFocused.value = false
  emit('blur', event)
}

const handleInput = (event: Event) => {
  const target = event.target as HTMLInputElement
  emit('input', event)
  emit('update:modelValue', target.value)
}

const handleChange = (event: Event) => {
  emit('change', event)
}

// Dynamic classes
const wrapperClasses = computed(() => {
  const classes = ['titan-datepicker-wrapper', 'relative']

  if (props.class) {
    classes.push(props.class)
  }

  return classes.join(' ')
})

const inputClasses = computed(() => {
  const classes = [
    // Base styles
    'w-full',
    'border-b-2',
    'bg-transparent',
    'pb-2',
    'pr-8', // Extra padding for the icon
    'text-base',
    'leading-6',
    'transition-all',
    'duration-200',
    'ease-in-out',
    'outline-none',
    'appearance-none',

    // Typography - inherit from parent
    'font-medium',

    // Focus styles
    'focus:outline-none',

    // Date input specific styles
    '[color-scheme:light]', // Ensure calendar icon matches theme
  ]

  // Size variants with floating label considerations
  if (hasFloatingLabel.value) {
    // When we have a floating label, use fixed top padding for label space
    classes.push('pt-6')

    switch (props.size) {
      case 'sm':
        classes.push('pb-2', 'text-sm')
        break
      case 'lg':
        classes.push('pb-4', 'text-lg')
        break
      default: // md
        classes.push('pb-3', 'text-base')
    }
  } else {
    // No floating label, use normal padding
    switch (props.size) {
      case 'sm':
        classes.push('py-2', 'text-sm')
        break
      case 'lg':
        classes.push('py-4', 'text-lg')
        break
      default: // md
        classes.push('py-3', 'text-base')
    }
  }

  // State-based styling
  if (hasError.value) {
    classes.push('border-red-500', 'focus:border-red-600')
  } else {
    classes.push(
      'border-gray-300',
      'focus:border-titan-green-800',
      'hover:border-gray-400'
    )
  }

  if (props.disabled) {
    classes.push(
      'cursor-not-allowed',
      'bg-gray-50',
      'border-gray-300',
      'text-gray-500'
    )
  } else if (props.readonly) {
    classes.push(
      'cursor-default'
    )
  }

  // Add class to hide placeholder when empty and not focused
  if (shouldHidePlaceholder.value) {
    classes.push('titan-datepicker-hide-placeholder')
  }

  return classes.join(' ')
})

const floatingLabelClasses = computed(() => {
  const classes = [
    'absolute',
    'left-0',
    'transition-all',
    'duration-200',
    'ease-in-out',
    'origin-left',
    'pointer-events-none',
    'select-none',
    'truncate',
    'max-w-full',
  ]

  // Floating state
  const shouldFloat = isFocused.value || hasValue.value || !!props.placeholder

  if (shouldFloat) {
    classes.push(
      'text-xs',
      'font-medium',
      'top-0',
      'scale-90'
    )

    // Color when floating
    if (hasError.value) {
      classes.push('text-red-600')
    } else if (isFocused.value) {
      classes.push('text-titan-green-800')
    } else {
      classes.push('opacity-70')
    }
  } else {
    classes.push(
      'text-base',
      'font-normal',
      'scale-100'
    )

    // Position label exactly where native placeholder would appear
    // Native placeholder aligns with text baseline = pt-6 padding
    classes.push('top-6')

    // Color when not floating
    if (hasError.value) {
      classes.push('text-red-500')
    } else {
      classes.push('opacity-60')
    }
  }

  return classes.join(' ')
})
</script>

<style scoped>
.error-fade-enter-active,
.error-fade-leave-active {
  transition: all 0.2s ease-in-out;
}

.error-fade-enter-from {
  opacity: 0;
  transform: translateY(-4px);
}

.error-fade-leave-to {
  opacity: 0;
  transform: translateY(-4px);
}

/* Hide the native date input calendar icon since we have our own */
input[type="date"]::-webkit-calendar-picker-indicator {
  opacity: 0;
  position: absolute;
  right: 0;
  width: 20px;
  height: 20px;
  cursor: pointer;
  z-index: 10;
}

/* Firefox */
input[type="date"]::-moz-calendar-picker {
  opacity: 0;
}

/* Hide the clear button */
input[type="date"]::-webkit-clear-button {
  display: none;
}

/* Hide the inner spin button */
input[type="date"]::-webkit-inner-spin-button {
  display: none;
}

/* Improve text rendering for date inputs */
input[type="date"] {
  -webkit-appearance: none;
  -moz-appearance: textfield;
  appearance: none;
}

/* Ensure consistent text color and remove default styling */
input[type="date"]::-webkit-datetime-edit {
  color: inherit;
  padding: 0;
}

input[type="date"]::-webkit-datetime-edit-fields-wrapper {
  padding: 0;
}

input[type="date"]::-webkit-datetime-edit-text {
  color: inherit;
  padding: 0;
}

input[type="date"]::-webkit-datetime-edit-month-field,
input[type="date"]::-webkit-datetime-edit-day-field,
input[type="date"]::-webkit-datetime-edit-year-field {
  color: inherit;
}

/* Ensure the custom icon is clickable */
.titan-datepicker-wrapper input[type="date"] {
  position: relative;
}

/* Hide placeholder text for empty date inputs using JavaScript-controlled class */
.titan-datepicker-hide-placeholder {
  color: transparent !important;
}

/* Hide specific WebKit date input parts for empty inputs using JavaScript-controlled class */
.titan-datepicker-hide-placeholder::-webkit-datetime-edit {
  color: transparent !important;
}

.titan-datepicker-hide-placeholder::-webkit-datetime-edit-fields-wrapper {
  color: transparent !important;
}

.titan-datepicker-hide-placeholder::-webkit-datetime-edit-text {
  color: transparent !important;
}

.titan-datepicker-hide-placeholder::-webkit-datetime-edit-month-field {
  color: transparent !important;
}

.titan-datepicker-hide-placeholder::-webkit-datetime-edit-day-field {
  color: transparent !important;
}

.titan-datepicker-hide-placeholder::-webkit-datetime-edit-year-field {
  color: transparent !important;
}

/* Show content when focused (override the hide class) */
input[type="date"]:focus {
  color: inherit !important;
}

input[type="date"]:focus::-webkit-datetime-edit {
  color: inherit !important;
}

input[type="date"]:focus::-webkit-datetime-edit-fields-wrapper {
  color: inherit !important;
}

input[type="date"]:focus::-webkit-datetime-edit-text {
  color: inherit !important;
}

input[type="date"]:focus::-webkit-datetime-edit-month-field {
  color: inherit !important;
}

input[type="date"]:focus::-webkit-datetime-edit-day-field {
  color: inherit !important;
}

input[type="date"]:focus::-webkit-datetime-edit-year-field {
  color: inherit !important;
}
</style>