<script setup lang="ts">
import Select from '@/components/Select.vue';
import DatePicker from '@/components/DatePicker.vue';
import {
  selectedUid,
  selectedUp3Posko,
  selectedPosko,
  fetchUid,
  fetchMedia,
  itemsUid,
  itemsUp3,
  itemsPosko,
  itemsMedia
} from './reference';
import { onMounted, ref, watch } from 'vue';

const uidPlaceholder = 'Semua Unit Induk Distribusi/Wilayah'
const up3Placeholder = 'Semua Unit Pelaksanaan Pelayanan Pelanggan'
const poskoPlaceholder = 'Semua Posko'
const mediaPlaceholder = 'Semua Media'
const up3 = ref({ id: 0, name: up3Placeholder })
const uid = ref({ id: 0, name: uidPlaceholder })
const posko = ref({ id: 0, name: poskoPlaceholder })
const media = ref({ id: '', name: mediaPlaceholder })
const emit = defineEmits(['update:filters'])
const data = ref({
  uid: uid.value,
  up3: up3.value,
  posko: posko.value,
  media: media.value,
  periode: ''
})

watch(data.value, (value) => {
  emit('update:filters', value)
})

const setUid = (value: any) => {
  uid.value = value
  selectedUid(value)
  up3.value = { id: 0, name: up3Placeholder }
  data.value.uid = value
}

const setUp3 = (value: any) => {
  up3.value = value
  selectedUp3Posko(value)
  posko.value = { id: 0, name: poskoPlaceholder }
  data.value.up3 = value
}

const setPosko = (value: any) => {
  posko.value = value
  selectedPosko(value)
  data.value.posko = value
}

const setMedia = (value: any) => {
  media.value = value
  data.value.media = value
}

onMounted(() => {
  emit('update:filters', data.value)
  fetchUid()
  fetchMedia()
})
</script>

<template>
  <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
    <div class="flex flex-col flex-1 space-y-2">
      <label class="filter-input-label">Unit Induk Distribusi/Wilayah:</label>

      <Select :data="itemsUid" @update:selected="setUid($event)" :placeholder="uidPlaceholder" :selected="uid" />
    </div>

    <div class="flex flex-col flex-1 space-y-2">
      <label class="filter-input-label">Unit Pelaksanaan Pelayanan Pelanggan:</label>

      <Select :data="itemsUp3" @update:selected="setUp3($event)" :placeholder="up3Placeholder" :selected="up3" />
    </div>

    <div class="flex flex-col flex-1 space-y-2">
      <label class="filter-input-label">Posko:</label>

      <Select :data="itemsPosko" @update:selected="setPosko($event)" :placeholder="poskoPlaceholder"
        :selected="posko" />
    </div>

    <div class="flex flex-col flex-1 space-y-2">
      <label class="filter-input-label">Media:</label>

      <Select :selected="media" @update:selected="setMedia($event)" :placeholder="mediaPlaceholder"
        :data="itemsMedia" />
    </div>

    <div class="flex flex-col flex-1 space-y-2">
      <label class="filter-input-label">Periode Tanggal:</label>

      <DatePicker @update:date-value="(value) => (data.periode = value)" />
    </div>
  </div>

</template>
