<script setup>
import AdminLayout from '@/Layouts/Admin/AppLayout.vue';
import { useForm } from '@inertiajs/inertia-vue3';
import { usePage } from '@inertiajs/inertia-vue3';
import { ref, reactive, watch, onMounted } from 'vue';
import { Form as VeeForm, Field, ErrorMessage, defineRule, configure } from 'vee-validate';
import { localize } from '@vee-validate/i18n';
import '@vueform/multiselect/themes/default.css';
import '@vueform/toggle/themes/default.css';
import moment from 'moment';

const page = usePage();
const props = defineProps(['data']);
const state = reactive({
  model: {}
});

onMounted(() => {
  //console.log('List user', props.data.users);
  console.log('title', props.data.title);
  if (props.data.isEdit) {
    // For edit mode, load the ticket data and convert date strings to Date objects
    const ticket = props.data.dateTicket;
    state.model = {
      ...ticket,
      issued_at: ticket.issued_at ? new Date(ticket.issued_at) : null,
      expires_at: ticket.expires_at ? new Date(ticket.expires_at) : null,
      used_at: ticket.used_at ? new Date(ticket.used_at) : null,
    };
  } else {
    // For create mode, set a default issued_at date
    state.model.issued_at = new Date();
  }
});

configure({
  generateMessage: localize({
    en: {
      fields: {
        user_id:{
          required: 'ユーザーを選択してください。'
        },
        type: { 
          required: '種別を選択してください。'
        },
        issued_at: {
          required: '発行日時を入力してください。'
        },
      }
    }
  })
});

// Custom validation rule cho used_at
defineRule('used_at_between', (value, [issuedAt, expiresAt]) => {
  if (!value || !issuedAt || !expiresAt) return true;
  
  const used = moment(value);
  const issued = moment(issuedAt);
  const expires = moment(expiresAt);
  
  if (used.isBefore(issued) || used.isAfter(expires)) {
    return '使用日時は発行日時と有効期限の間である必要があります。';
  }
  
  return true;
});

const onInvalidSubmit = ({ errors }) => {
  let firstInputError = Object.entries(errors)[0][0];
  let ele = document.querySelector(`[name="${firstInputError}"]`);
  if (!ele || ele.classList.contains('hidden') || ele.type === 'hidden') {
    ele = ele.closest('div');
  }
  if (ele) {
    ele.focus();
    window.scrollTo({ top: ele.offsetTop - 150, behavior: 'smooth' });
  }
};

const onSubmit = () => {
  const dataSubmit = { ...state.model };  
  console.log('Data submit',dataSubmit);
  if (props.data.isEdit) {
    useForm(dataSubmit).put(route('admin.dateTicket.update', props.data.dateTicket.id));
    return;
  }
  useForm(dataSubmit).post(route('admin.dateTicket.store'));
};
</script>

<template>
  <AdminLayout>
    <template #content>
      <Panel :header="props.data.title ">
        <VeeForm as="div" v-slot="{ handleSubmit }" @invalid-submit="onInvalidSubmit">
          <form @submit="handleSubmit($event, onSubmit)" class="form-data">

            <div class="form-group">
              <label class="form-label" require>ユーザー: </label>
              <div class="form-input">
                <Field name="user_id" rules="required" v-model="state.model.user_id" v-slot="{ field, meta, handleChange }">
                  <Select
                    v-model="state.model.user_id"
                    :options="props.data.users"
                    optionLabel="email"
                    optionValue="id"
                    placeholder="ユーザーを選択してください"
                    class="w-full"
                    filter
                    emptyFilterMessage="データが見つかりません"
                    name="user_id"
                    showClear
                    :class="{ 'p-invalid': !meta.valid && meta.touched }"
                    @update:modelValue="
                      (val) => {
                        handleChange(val);
                        state.model.status = val;
                      }
                    "
                  />
                  <ErrorMessage class="p-error" name="user_id" />
                </Field>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label" require>種別: </label>
              <div class="form-input">
                <Field name="type" rules="required" v-model="state.model.type" v-slot="{ field, meta, handleChange }">
                  <Select
                    v-model="state.model.type"
                    :options="props.data.type"
                    optionLabel="label"
                    optionValue="value"
                    placeholder="種別を選択してください"
                    class="w-1/3"
                    filter
                    emptyFilterMessage="データが見つかりません"
                    name="type"
                    showClear
                    :class="{ 'p-invalid': !meta.valid && meta.touched }"
                    @update:modelValue="
                      (val) => {
                        handleChange(val);
                        state.model.status = val;
                      }
                    "
                  />
                  <ErrorMessage class="p-error" name="type" />
                </Field>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label" require>発行日時: </label>
              <div class="form-input">
                <Field name="issued_at" rules="required" v-model="state.model.issued_at" v-slot="{ field, meta, handleChange }">
                  <Calendar v-bind="field" v-model="state.model.issued_at" dateFormat="yy/mm/dd" showTime showSeconds hourFormat="24"  placeholder="" class="w-1/2" showIcon :maxDate="new Date()" :class="{ 'p-invalid': !meta.valid && meta.touched }" @update:model-value="handleChange" panelClass="custom-calendar-panel" />
                  <ErrorMessage class="p-error" name="issued_at" />
                </Field>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">有効期限: </label>
              <div class="form-input">
                <Field name="expires_at" rules="" v-model="state.model.expires_at" v-slot="{ field, meta, handleChange }">
                  <Calendar v-bind="field" v-model="state.model.expires_at" dateFormat="yy/mm/dd" showButtonBar showTime showSeconds hourFormat="24" placeholder="" class="w-1/2" showIcon :minDate="new Date()" :class="{ 'p-invalid': !meta.valid && meta.touched }" @update:model-value="handleChange" panelClass="custom-calendar-panel" />
                  <ErrorMessage class="p-error" name="expires_at"/> 
                </Field>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label" >使用日時: </label>
              <div class="form-input">
                <Field 
                  name="used_at" 
                  :rules="`used_at_between:${state.model.issued_at},${state.model.expires_at}`" 
                  v-model="state.model.used_at" 
                  v-slot="{ field, meta, handleChange }"
                >
                  <Calendar 
                    v-bind="field" 
                    v-model="state.model.used_at" 
                    dateFormat="yy/mm/dd"
                    showButtonBar
                    showTime 
                    showSeconds 
                    hourFormat="24" 
                    placeholder="" 
                    class="w-1/2" 
                    showIcon 
                    :minDate="state.model.issued_at || new Date()" 
                    :maxDate="state.model.expires_at" 
                    :class="{ 'p-invalid': !meta.valid && meta.touched }" 
                    @update:model-value="handleChange" 
                    panelClass="custom-calendar-panel"
                  />
                  <ErrorMessage class="p-error" name="used_at"/>
                </Field>
              </div>
            </div>

            <div class="form-action">
              <Link :href="page.props.data?.urlBack || route('admin.dateTicket.index')">
                <Button label="キャンセル" icon="pi pi-arrow-left" class="btn-action" />
              </Link>
              <Button label="保存" type="submit" icon="pi pi-save" class="btn-action" />
            </div>
          </form>
        </VeeForm>
      </Panel>
    </template>
  </AdminLayout>
</template>

<style>
.custom-calendar-panel {
  transform: translateX(50px) !important;
}
</style>

<style scoped>
.form-input {
  display: block;
}

.p-error {
  display: block;
  margin-top: 5px;
  color: #dc3545;
  font-size: 0.875rem;
}
</style>