<template>
  <div class="flex flex-col md:flex-row gap-4">
    <!-- Presets -->
    <div class="flex-1">
      <label class="text-xs text-[var(--brand-text-muted)] block mb-1">Rango rápido</label>
      <UFieldGroup>
        <UButton
          color="neutral"
          variant="subtle"
          :label="currentPresetLabel"
          class="flex-1"
          disabled
        />
        <UDropdownMenu :items="dropdownItems" :popper="{ placement: 'bottom-end' }">
          <UButton
            color="neutral"
            variant="outline"
            icon="i-lucide-chevron-down"
            square
          />
        </UDropdownMenu>
      </UFieldGroup>
    </div>

    <!-- Fechas manuales -->
    <div class="grid grid-cols-2 gap-4 flex-1">
      <div>
        <label class="text-xs text-[var(--brand-text-muted)]">Fecha desde</label>
        <UInput :model-value="fechaDesde" type="date" @input="(e: Event) => onManualDateChange('desde', e)" />
      </div>
      <div>
        <label class="text-xs text-[var(--brand-text-muted)]">Fecha hasta</label>
        <UInput :model-value="fechaHasta" type="date" @input="(e: Event) => onManualDateChange('hasta', e)" />
      </div>
    </div>

    <div class="flex items-end">
      <UButton
        :ui="{ base: 'bg-[var(--brand-primary-strong)] text-[var(--brand-bg)] border border-[var(--brand-primary)] hover:bg-[var(--brand-primary)] hover:border-[var(--brand-accent)]' }"
        @click="setToday"
        size="sm"
      >
        Resetear a Hoy
      </UButton>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, watch, onMounted } from 'vue'

type PresetValue =
  | '' | 'custom' | 'hoy' | 'semana' | 'mes' | 'ytd'
  | 'cosecha-20-21' | 'cosecha-21-22' | 'cosecha-22-23'
  | 'cosecha-23-24' | 'cosecha-24-25' | 'cosecha-25-26'

interface Props {
  selectedPreset: PresetValue
  fechaDesde: string | null
  fechaHasta: string | null
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:selectedPreset': [value: PresetValue]
  'update:fechaDesde': [value: string | null]
  'update:fechaHasta': [value: string | null]
}>()

// Definir funciones antes del watch
const toLocalDateStr = (d: Date) => {
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

function selectPreset(preset: PresetValue) {
  console.log('selectPreset called with:', preset)
  emit('update:selectedPreset', preset)

  if (preset === '' || preset === 'custom') {
    emit('update:fechaDesde', null)
    emit('update:fechaHasta', null)
    console.log('Cleared dates')
    return
  }

  const now = new Date()
  const set = (sd: string, ed: string) => {
    emit('update:fechaDesde', sd)
    emit('update:fechaHasta', ed)
    console.log('Set dates:', sd, ed)
  }

  switch (preset) {
    case 'hoy': set(toLocalDateStr(now), toLocalDateStr(now)); break
    case 'semana': {
      const d = new Date(now)
      const day = d.getDay() || 7
      d.setDate(d.getDate() - (day - 1)) // lunes
      set(toLocalDateStr(d), toLocalDateStr(now))
      break
    }
    case 'mes': set(toLocalDateStr(new Date(now.getFullYear(), now.getMonth(), 1)), toLocalDateStr(now)); break
    case 'ytd': set(toLocalDateStr(new Date(now.getFullYear(), 0, 1)), toLocalDateStr(now)); break
    case 'cosecha-20-21': set('2020-09-25', '2021-09-24'); break
    case 'cosecha-21-22': set('2021-09-25', '2022-09-24'); break
    case 'cosecha-22-23': set('2022-09-25', '2023-09-24'); break
    case 'cosecha-23-24': set('2023-09-25', '2024-09-24'); break
    case 'cosecha-24-25': set('2024-09-25', '2025-09-09'); break
    case 'cosecha-25-26': set('2025-09-10', toLocalDateStr(now)); break
  }
}

function onManualDateChange(type: 'desde' | 'hasta', event: Event) {
  const target = event.target as HTMLInputElement
  const value = target.value || null

  // Si el usuario modifica las fechas manualmente, cambiar a "Personalizado"
  emit('update:selectedPreset', 'custom')

  // Actualizar la fecha correspondiente
  if (type === 'desde') {
    emit('update:fechaDesde', value)
  } else {
    emit('update:fechaHasta', value)
  }

  console.log(`Manual date change (${type}):`, value, 'preset set to custom')
}

function setToday() {
  selectPreset('hoy')
  console.log('Preset reset to today')
}

// Watch para aplicar el preset cuando cambia (incluyendo el valor inicial)
watch(() => props.selectedPreset, (newPreset) => {
  if (newPreset !== '' && newPreset !== 'custom') {
    selectPreset(newPreset)
  }
}, { immediate: true })

const currentPresetLabel = computed(() => {
  switch (props.selectedPreset) {
    case '': return 'Sin filtro'
    case 'custom': return 'Personalizado'
    case 'hoy': return 'Hoy'
    case 'semana': return 'Esta Semana'
    case 'mes': return 'Este Mes'
    case 'ytd': return 'YTD'
    case 'cosecha-20-21': return 'Cosecha 20-21'
    case 'cosecha-21-22': return 'Cosecha 21-22'
    case 'cosecha-22-23': return 'Cosecha 22-23'
    case 'cosecha-23-24': return 'Cosecha 23-24'
    case 'cosecha-24-25': return 'Cosecha 24-25'
    case 'cosecha-25-26': return 'Cosecha 25-26'
    default: return 'Seleccionar rango'
  }
})

const dropdownItems = [
  {
    label: 'Sin filtro',
    onSelect: () => {
      selectPreset('')
    }
  },
  {
    label: 'Rápidos',
    children: [
      { label: 'Hoy', onSelect: () => { selectPreset('hoy') } },
      { label: 'Esta Semana', onSelect: () => { selectPreset('semana') } },
      { label: 'Este Mes', onSelect: () => { selectPreset('mes') } },
      { label: 'YTD', onSelect: () => { selectPreset('ytd') } }
    ]
  },
  {
    label: 'Cosechas',
    children: [
      { label: 'Cosecha 20-21 (25 Sep 2020)', onSelect: () => { selectPreset('cosecha-20-21') } },
      { label: 'Cosecha 21-22 (25 Sep 2021)', onSelect: () => { selectPreset('cosecha-21-22') } },
      { label: 'Cosecha 22-23 (25 Sep 2022)', onSelect: () => { selectPreset('cosecha-22-23') } },
      { label: 'Cosecha 23-24 (25 Sep 2023)', onSelect: () => { selectPreset('cosecha-23-24') } },
      { label: 'Cosecha 24-25 (25 Sep 2024)', onSelect: () => { selectPreset('cosecha-24-25') } },
      { label: 'Cosecha 25-26 (10 Sep 2025 → hoy)', onSelect: () => { selectPreset('cosecha-25-26') } }
    ]
  }
]
</script>
