<script setup lang="ts">
import Select from '@/components/Select.vue'
import DatePicker from '@/components/DatePicker.vue'
import InlineRadioGroup from '@/components/Form/InlineRadioGroup.vue'

import { onMounted, ref, watch } from 'vue'
import {
  selectedUid,
  selectedUp3Posko,
  selectedPosko,
  fetchUid,
  itemsUid,
  itemsUp3,
  itemsPosko
} from './reference'

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

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

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

const setUp3 = (value: any) => {
  uppp.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
}

onMounted(() => {
  fetchUid()
  emit('update:filters', data.value)
})
</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 @update:selected="setUid($event)" :data="itemsUid" :placeholder="uidPlaceholder" />
    </div>

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

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

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

      <Select @update:selected="setPosko($event)" :data="itemsPosko" :placeholder="poskoPlaceholder"
        :selected="posko" />
    </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 class="flex flex-col flex-1 space-y-2">
      <label class="filter-input-label">Group By Kode Unit Distribusi:</label>

      <InlineRadioGroup @update:group-value="(value) => (data.groupBy = value.id === 2)" :radio-items="[
        { id: 1, title: 'Tidak', checked: true },
        { id: 2, title: 'Ya, Grupkan' }
      ]" />
    </div>
  </div>

</template>
