<template>
  <form @submit.prevent="onSubmit" class="bg-white dark:bg-dark-grey rounded-lg p-1">
    <div class="p-5 pr-3 flex flex-col max-h-[90vh] overflow-y-scroll autocomplete">
      <div class="flex justify-between items-center">
        <h4 class="text-black dark:text-white font-bold text-lg">
          {{ systemStore.appointmentForm.edit ? 'Edit Appointment' : 'Add New Appointment' }}
        </h4>
      </div>

      <!--  edit  -->
      <div v-if="systemStore.appointmentForm.edit" class="flex flex-wrap">
        <div class="card lg:w-12/12 shadow-xl w-full border-x border-y border-light-grey">
          <div class="card-body">
            <Datepicker v-model="selectedDate" range multiCalendars text-input 
                :partial-range="false" 
                />
            <div class="relative flex flex-col gap-2 w-full py-4">
              <label for="LastName" class="text-medium-grey dark:text-white text-xs font-bold">Last Name :
                <span class="text-medium-grey text-red text-xs font-bold">(Unchangeable value)</span>
              </label>
              <input type="text" id="inputLastName" ref="inputLastName" readonly
                class="peer px-4 py-2 text-black dark:text-white dark:bg-dark-grey text-sm rounded transition-colors outline outline-1 outline-medium-grey/25
                    cursor-pointer hover:outline-main-purple focus:outline-main-purple placeholder:text-black/25 dark:placeholder:text-white/25"
                    v-model="search.patient.lastName"
              />
              <label for="FirstName" class="text-medium-grey dark:text-white text-xs font-bold">First Name :
                <span class="text-medium-grey text-red text-xs font-bold">(Unchangeable value)</span>
              </label>
              <input type="text" id="inputFirstName" ref="inputFirstName" readonly
                class="peer px-4 py-2 text-black dark:text-white dark:bg-dark-grey text-sm rounded transition-colors outline outline-1 outline-medium-grey/25
                    cursor-pointer hover:outline-main-purple focus:outline-main-purple placeholder:text-black/25 dark:placeholder:text-white/25"
                    v-model="search.patient.firstName"
              />
              <label for="DOB" class="text-medium-grey dark:text-white text-xs font-bold">DOB(Date of birth) :
                <span class="text-medium-grey text-red text-xs font-bold">(Unchangeable value)</span>
              </label>
              <input type="text" id="inputDOB" ref="inputDOB" readonly
                class="peer px-4 py-2 text-black dark:text-white dark:bg-dark-grey text-sm rounded transition-colors outline outline-1 outline-medium-grey/25
                    cursor-pointer hover:outline-main-purple focus:outline-main-purple placeholder:text-black/25 dark:placeholder:text-white/25"
                    v-model="search.patient.dob"
              />
              <label for="CellPhone" class="text-medium-grey dark:text-white text-xs font-bold">Cell Phone :
                <span class="text-medium-grey text-red text-xs font-bold">(Unchangeable value)</span>
              </label>
              <input type="text" id="inputCellPhone" ref="inputCellPhone" readonly
                class="peer px-4 py-2 text-black dark:text-white dark:bg-dark-grey text-sm rounded transition-colors outline outline-1 outline-medium-grey/25
                    cursor-pointer hover:outline-main-purple focus:outline-main-purple placeholder:text-black/25 dark:placeholder:text-white/25"
                    v-model="search.patient.cellPhone"
              />
            </div>
            <BaseTextarea v-model="search.description" inputName="Description" placeholder="e.g. Description" />
          </div>
        </div>
      </div>

      <!--  save  -->
      <div v-else class="flex flex-wrap">
        <div class="card lg:w-12/12 shadow-xl w-full border-x border-y border-light-grey">
          <div class="card-body">
            <!-- <h2 class="text-2xl font-semibold text-center">Search</h2> -->
            <div class="grid grid-cols-2 gap-4">
              <label for="SearchField" class="text-medium-grey dark:text-white text-xs font-bold">Search Field :
                <select id="SearchField" v-model="searchField"
                  class="peer px-4 py-2 text-black dark:text-white dark:bg-dark-grey text-sm rounded transition-colors outline outline-1 outline-medium-grey/25
                      cursor-pointer hover:outline-main-purple focus:outline-main-purple placeholder:text-black/25 dark:placeholder:text-white/25"
                >
                  <option value="lastName">Last Name</option>
								  <option value="firstName">First Name</option>
              		<option value="dob">DOB(Date of birth)</option>
                </select>
              </label>
              <label for="SearchValue" class="text-medium-grey dark:text-white text-xs font-bold">Search Value :
                  <input v-if="searchField === 'dob'" type="text" id="SearchValue"
                    class="peer px-4 py-2 text-black dark:text-white dark:bg-dark-grey text-sm rounded transition-colors outline outline-1 outline-medium-grey/25
                        cursor-pointer hover:outline-main-purple focus:outline-main-purple placeholder:text-black/25 dark:placeholder:text-white/25"
                        v-model="searchValue"
                        size=10 maxlength=10  onkeydown="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')" 
                  />
                  <input v-else type="text" id="SearchValue"
                    class="peer px-4 py-2 text-black dark:text-white dark:bg-dark-grey text-sm rounded transition-colors outline outline-1 outline-medium-grey/25
                        cursor-pointer hover:outline-main-purple focus:outline-main-purple placeholder:text-black/25 dark:placeholder:text-white/25"
                        v-model="searchValue"
                  />
              </label>
            </div>
            <div class="relative flex flex-col gap-2 w-full py-4">
              <EasyDataTable 
                :headers="headers" 
                :items="patientsStore.getPatients" 
                :rows-per-page="5" 
                :loading="patientsStore.getLoading" 
                :search-field="searchField"
                :search-value="searchValue"
                @click-row="tableRowClicked"
                border-cell 
                buttons-pagination>
                <template #item-sex="item">{{ item.sex == "0" ? 'male' : 'female' }}</template>
                <!-- <template #item-actions="item">
                  <div class="operation-wrapper">
                    <button class="btn btn-xs btn-error" @click="deleteItem(item)"><i class="fas fa-trash-alt"></i>Delete</button>
                    <button class="btn btn-xs btn-warning" @click="editItem(item)"><i class="fas fa-edit"></i>Update</button>
                  </div>
                </template> -->
              </EasyDataTable>
            </div>
            <hr class="pb-5">
            <Datepicker v-model="selectedDate" range multiCalendars text-input 
                :partial-range="false" 
                />
                <div class="grid grid-cols-4 gap-4">
                  <label for="LastName" class="text-medium-grey dark:text-white text-xs font-bold">Last Name :
                    <input type="text" id="inputLastName" ref="inputLastName" readonly
                        class="peer px-4 py-2 text-black dark:text-white dark:bg-dark-grey text-sm rounded transition-colors outline outline-1 outline-medium-grey/25
                            cursor-pointer hover:outline-main-purple focus:outline-main-purple placeholder:text-black/25 dark:placeholder:text-white/25"
                            v-model="search.patient.lastName"
                    />
                  </label>
                  <label for="FirstName" class="text-medium-grey dark:text-white text-xs font-bold">First Name :
                    <input type="text" id="inputFirstName" ref="inputFirstName" readonly
                        class="peer px-4 py-2 text-black dark:text-white dark:bg-dark-grey text-sm rounded transition-colors outline outline-1 outline-medium-grey/25
                            cursor-pointer hover:outline-main-purple focus:outline-main-purple placeholder:text-black/25 dark:placeholder:text-white/25"
                            v-model="search.patient.firstName"
                    />
                  </label>
                  <label for="DOB" class="text-medium-grey dark:text-white text-xs font-bold">DOB(Date of birth) :
                    <input type="text" id="inputDOB" ref="inputDOB" readonly
                        class="peer px-4 py-2 text-black dark:text-white dark:bg-dark-grey text-sm rounded transition-colors outline outline-1 outline-medium-grey/25
                            cursor-pointer hover:outline-main-purple focus:outline-main-purple placeholder:text-black/25 dark:placeholder:text-white/25"
                            v-model="search.patient.dob"
                    />
                  </label>
                  <label for="CellPhone" class="text-medium-grey dark:text-white text-xs font-bold">CellPhone :
                    <input type="text" id="CellPhone" ref="searchCellPhone" readonly
                        class="peer px-4 py-2 text-black dark:text-white dark:bg-dark-grey text-sm rounded transition-colors outline outline-1 outline-medium-grey/25
                            cursor-pointer hover:outline-main-purple focus:outline-main-purple placeholder:text-black/25 dark:placeholder:text-white/25"
                            v-model="search.patient.cellPhone"
                    />
                  </label>
                </div>
                <BaseTextarea v-model="search.description" inputName="Description" placeholder="e.g. Description" />
          </div>
        </div>

    </div>

      
      <div v-if="systemStore.appointmentForm.edit">
        <div class="grid grid-cols-2 gap-4">
          <ButtonPrimaryLarge type="submit">Save Changes</ButtonPrimaryLarge>
          <ButtonPrimaryLarge @click.stop="deleteItem(search)">Delete</ButtonPrimaryLarge>
        </div>
      </div>
      <div v-else>
        <ButtonPrimaryLarge type="submit">Create Task</ButtonPrimaryLarge>
      </div>
    </div>
  </form>
</template>

<script>
import { useBoardsStore } from '@/store/boards.js';
import { usePatientsStore } from '@/store/patients.js';
import { useSystemStore } from '@/store/system.js';
import BaseSelect from '@/components/form/BaseSelect.vue';
import BaseInput from '@/components/form/BaseInput.vue';
import BaseTextarea from '../form/BaseTextarea.vue';
import IconCross from '../icons/IconCross.vue';
import ButtonPrimaryLarge from '../buttons/PrimaryLarge.vue';
import ButtonSecondaryLarge from '../buttons/SecondaryLarge.vue';
import Datepicker from '@vuepic/vue-datepicker';
import '@vuepic/vue-datepicker/dist/main.css';
import { INITIAL_EVENTS, createEventId } from '@/services/utils/calendar-utils'
import { mapState } from "vuex";

export default {
	name: "AppointmentForm",
	data() {
		return {
      boardsStore: useBoardsStore(),
      patientsStore: usePatientsStore(),
      systemStore: useSystemStore(),

      selectedDate: null,
      search: {
        status: 'Appointment',
        startdt: '',
        enddt: '',
        description: '',
        patient: {
          lastName: '',
          firstName: '',
          dob: '',
          cellPhone: '',
        },
      },

      headers: [
        { text: "Last Name", value: "lastName" },
				{ text: "First Name", value: "firstName" },
				{ text: "SSN", value: "ssn" },
				{ text: "DOB", value: "dob" },
				{ text: "Gender", value: "sex" },
				{ text: "CellPhone", value: "cellPhone" },
				{ text: "City", value: "city" },
				{ text: "ACTIONS", value: "actions" }
			],
      searchField: "lastName",
      searchValue: "",

		};
	},
	mounted() {
    // document.addEventListener('click', this.handleClickOutside);

    if (this.systemStore.appointmentForm.edit) {
      this.search = this.boardsStore.transCalendarEventToJson(this.boardsStore.getSelectedEvent.event);
      this.selectedDate = [this.search.startdt, this.search.enddt];
    }
    else{
      const calendarInfo = this.boardsStore.getSelectedDate;
      this.selectedDate = [calendarInfo.start, calendarInfo.end];
    }
    
  },
  unmounted() {
    // document.removeEventListener('click', this.handleClickOutside)
  },
	methods: {
    tableRowClicked(row) {
      this.search.patient = row;
    },
    onSubmit() {
      if (this.validate()) {
        if (typeof this.selectedDate[0] === 'object') {
          this.search.startdt = this.selectedDate[0].getTime();
          this.search.enddt = this.selectedDate[1].getTime();
        } else if (typeof this.selectedDate[0] == 'number') {
          this.search.startdt = this.selectedDate[0];
          this.search.enddt = this.selectedDate[1];
        }

        if (this.systemStore.appointmentForm.edit) {
          // boardsStore.saveTaskChanges({ task: form.task, column: form.column });
          this.boardsStore.updateByDataEvent(this.search, this.boardsStore.selectedEvent);

        } else {
          // boardsStore.getCurrentBoard[form.column].tasks.push(form.task);
          this.boardsStore.save(this.search);
        }
        this.systemStore.hideOverlay();
      }
    },
    deleteItem(data) {
      this.boardsStore.deleteByEvent(data, this.boardsStore.selectedEvent);
      this.systemStore.appointmentForm.visible = false;
      this.systemStore.hideOverlay();
    },
    validate() {
      let valid = true;

      //  등록된 환자가 아니고 신규 환자일 때,
      // if (this.search.title.trim().length === 0) {
      //   valid = false;
      //   searchTitle.value.error = true;
      // }
      // if (this.search.birthDate.trim().length === 0) {
      //   valid = false;
      //   searchBirthDate.value.error = true;
      // }
      // if (this.search.cellPhone.trim().length === 0) {
      //   valid = false;
      //   searchCellPhone.value.error = true;
      // }
      return valid
    }

	},
	components: {
		BaseSelect,
    BaseInput,
    BaseTextarea,
    ButtonPrimaryLarge,
    Datepicker
	},
	computed: {
		...mapState(["isRTL", "isAbsolute"]),

		// currentUser() {
		// 	return this.$store.state.auth.user;
		// },
	},

};
</script>