<script setup lang="ts">
import _ from 'lodash';
import { ref, onMounted } from 'vue';
import { computed } from 'vue';
import moment from 'moment';
import flatPickr from 'vue-flatpickr-component';
import 'flatpickr/dist/flatpickr.css';
import { German } from 'flatpickr/dist/l10n/de.js';
import rangePlugin from 'flatpickr/dist/plugins/rangePlugin.js';
import weekSelect from 'flatpickr/dist/plugins/weekSelect/weekSelect.js';

const props = defineProps({ modelValue: { type: Object, required: true } });
const emit = defineEmits(['update:modelValue']);

const value = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit('update:modelValue', value.value);
  },
});

let configBase = {
  wrap: true, // set wrap to true only when using 'input-group'
  dateFormat: 'Y-m-d',
  locale: German, // locale for this instance only
  plugins: [new weekSelect({})],
  weekNumbers: true,
};

const config = ref(
  _.merge(configBase, {
    defaultDate: value.data,
    getWeek: function (dateObj) {
      const current = moment(dateObj).startOf('isoWeek');     
      return `${current.isoWeekYear()}W${current.isoWeek().toString().padStart(2, '0')}`;
    },
    formatDate: (date, format, locale) => {
      const current = moment(date).startOf('isoWeek');      
      return `${current.isoWeekYear()}W${current.isoWeek().toString().padStart(2, '0')}`;
    },
    onReady: () => {
      console.log('start week', value.value);
    },
  }),
);

const config2 = ref({
  wrap: true, // set wrap to true only when using 'input-group'
  dateFormat: 'Y-m-d',
  defaultDate: value.data2,
  locale: German, // locale for this instance only
  plugins: [new weekSelect({})],
  weekNumbers: true,
  getWeek: function (dateObj) {
    const current = moment(dateObj).startOf('isoWeek');    
    return `${current.isoWeekYear()}W${current.isoWeek().toString().padStart(2, '0')}`;
  },
  formatDate: (date, format, locale) => {
    const current = moment(date).startOf('isoWeek');    
    return `${current.isoWeekYear()}W${current.isoWeek().toString().padStart(2, '0')}`;
  },
  onReady: function () {
    console.log('end week', value.value);
  },
});

onMounted(() => {
  console.log('   onMounted     ', props.modelValue); // don't use this keyword
});
</script>

<template>
  <div class="week-selector">
    <div class="form-group">
      <flat-pickr v-model="value.data" :config="config" class="form-control" placeholder="Select week1" name="date" />
    </div>
    ~
    <div class="form-group">
      <flat-pickr v-model="value.data2" :config="config2" class="form-control" placeholder="Select week2" name="date2" />
    </div>
  </div>
</template>

<style scoped>
.select-input {
  padding: 0.5rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 200px;
}
</style>
