<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 gap-6 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>
      <Datepicker v-model="selectedDate" range multiCalendars />
      <div class="text-white relative flex flex-col gap-2 w-full">
        <label for="Name" class="text-medium-grey dark:text-white text-xs font-bold">Search Name or BirthDate...</label>
        <input
          type="text"
          id="Name"
          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"
          @input="onChange"
          v-model="search"
          @keydown.down="onArrowDown"
          @keydown.up="onArrowUp"
          @keydown.enter="onEnter"
          autocomplete="off"
        />
        <ul
          id="autocomplete-results"
          v-show="isOpen"
          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 autocomplete-results"
        >
          <li
            class="loading"
            v-if="isLoading"
          >
            Loading results...
          </li>
          <li
            v-else
            v-for="(result, i) in results"
            :key="i"
            :id="result.id"
            @click="setResult(result)"
            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 autocomplete-result"
            :class="{ 'is-active': i === arrowCounter }"
          >
          BirthDate: {{ result.birthDate }} / Name: {{ result.name }}
          </li>
        </ul>
        <hr class="py-4">
        <p
          v-if="registPatient !== null"
          class="text-medium-grey dark:text-white text-xs font-bold"
        >
        [Registered] 
          <br><span class="font-semibold px-4 py-2 ">Name: {{ registPatient.name }}</span> 
          <br><span class="font-semibold px-4 py-2 ">BirthDate: {{ registPatient.birthDate }}</span>
          <br><span class="font-semibold px-4 py-2 ">CellPhone: {{ registPatient.cellPhone }}</span>
        </p>
        <p
          v-else
          class="text-medium-grey dark:text-white text-xs font-bold"
        >
        [New] 
          <br><span ref="searchName" class="font-semibold px-4 py-2">Name: {{ search }}</span>
          <br><label for="BirthDate" class="text-medium-grey dark:text-white text-xs font-bold px-4 py-2">BirthDate</label>
          <input
            ref="searchBirthDate"
            type="text"
            id="BirthDate"
            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="searchBirthDate"
          />
          <br><label for="CellPhone" class="text-medium-grey dark:text-white text-xs font-bold px-4 py-2">CellPhone</label>
          <input
            ref="searchCellPhone"
            type="text"
            id="CellPhone"
            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="searchCellPhone"
          />
        </p>
      </div>

      <BaseTextarea v-model="form.task.description" inputName="Symptom"
        placeholder="e.g. Description" />
      <ButtonPrimaryLarge type="submit">
        {{ systemStore.appointmentForm.edit ? 'Save Changes' : 'Create Task' }}
      </ButtonPrimaryLarge>
    </div>
  </form>
</template>

<script>
import { useBoardsStore } from '@/store/boards.js';
import { usePatientsStore } from '@/store/patients.js';
import { useManagementStore } from '@/store/management.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 { mapState } from "vuex";

export default {
	name: "AppointmentForm",
	data() {
		return {
      boardsStore: useBoardsStore(),
      patientsStore: usePatientsStore(),
      managementStore: useManagementStore(),
      systemStore: useSystemStore(),
      columnName: "",
      inputTitle: null,
      inputs: [],
      selectedDate: null,
      searchColumnName: ['Name', 'Phone'],
      isOpen: false,
      isLoading: false,
      arrowCounter: -1,
      search: "",
      searchBirthDate: "",
      searchCellPhone: "",
      countries: "",
      calendarInfo: null,
      items: [],
      results: [],
      registPatient: null,

      form: {
        task: {
          name: '',
          description: '',
          subtasks: [{ title: '', isCompleted: false }, { title: '', isCompleted: false }]
        },
        column: 0
      }

		};
	},
  watch: {
    items: function (value, oldValue) {
      if (value.length !== oldValue.length) {
        this.results = value;
        this.isLoading = false;
      }
    },
  },
	mounted() {
    this.items = this.patientsStore.getPatients;
    document.addEventListener('click', this.handleClickOutside);

    this.calendarInfo = this.managementStore.getCurrentCalendarInfo;
    this.selectedDate = [this.calendarInfo.start, this.calendarInfo.end];

  },
  unmounted() {
    document.removeEventListener('click', this.handleClickOutside)
  },
	methods: {
    setResult(result) {
      this.search = result.name;
      this.isOpen = false;
      this.registPatient = null;
    },
    filterResults() {
      this.results = this.items.filter((item) => {
        return (item.name.toLowerCase().indexOf(this.search.toLowerCase()) > -1) || (item.birthDate.toLowerCase().indexOf(this.search.toLowerCase()) > -1);
      });
    },
		onChange() {
      this.$emit('input', this.search);
      this.filterResults();
      this.isOpen = true;
      this.registPatient = null;
    },
		handleClickOutside(event) {
      // console.log("handleClickOutside");
      if (!this.$el.contains(event.target)) {
        this.arrowCounter = -1;
      }
      this.isOpen = false;
      
      //  목록 중 마우스로 클릭했을 때,
      if(event.target.id !== undefined) {
        var patientList = this.items.filter((item) => {
          try {
            return item.id === Number(event.target.id); 
          } catch (e) {
            return false;
          }
        });
        if(patientList.length !== 0) this.registPatient = patientList[0];
        // console.log(this.registPatient);
      }
    },
    onArrowDown() {
      // console.log("onArrowDown");
      if (this.arrowCounter < this.results.length) {
        this.arrowCounter = this.arrowCounter + 1;
      }
      // console.log(this.arrowCounter);
    },
    onArrowUp() {
      // console.log("onArrowUp");
      if (this.arrowCounter > 0) {
        this.arrowCounter = this.arrowCounter - 1;
      }
    },
    onEnter() {
      if(this.results[this.arrowCounter] !== undefined) {
        this.search = this.results[this.arrowCounter].name;
        this.registPatient = this.results[this.arrowCounter];
      }
      // console.log(this.search);
      this.isOpen = false;
      this.arrowCounter = -1;
    },

    onSubmit() {
      if (this.validate()) {
        if (this.systemStore.appointmentForm.edit) {
          // boardsStore.saveTaskChanges({ task: form.task, column: form.column });
          

          let calendarApi = this.calendarInfo.view.calendar
          calendarApi.unselect() // clear date selection
          calendarApi.addEvent({
            // id: calendarId++,
            title: this.search,
            start: this.calendarInfo.startStr,
            end: this.calendarInfo.endStr,
            allDay: this.calendarInfo.allDay
          });
          console.log(1);
        } else {
          // boardsStore.getCurrentBoard[form.column].tasks.push(form.task);
          console.log(this.registPatient);
          console.log(this.search);
          console.log(this.searchBirthDate);
          console.log(this.searchCellPhone);

          //  기존 환자가 아닐 때,
          if(this.registPatient === null) {
            let uploadData = {
              "name" : this.search,
              "status" : 1,
              "cellPhone" : this.searchCellPhone,
              "birthDate" : this.searchBirthDate,
              "startdt" : this.searchBirthDate,
              "enddt" : this.searchBirthDate,
              "symptom" : this.form.task.description,
              "patient_id" : null,
            }
            this.managementStore.save(uploadData);
          }
          //  기존 환자인 경우,
          else{
            let uploadData = {
              "name" : this.registPatient.name,
              "status" : 1,
              "cellPhone" : this.registPatient.cellPhone,
              "birthDate" : this.registPatient.birthDate,
              "startdt" : this.calendarInfo.start.getTime(),
              "enddt" : this.calendarInfo.end.getTime(),
              "symptom" : this.form.task.description,
              "patient_id" : this.registPatient.id,
            }
            console.log(uploadData);
            this.managementStore.save(uploadData);
          }

          let calendarApi = this.calendarInfo.view.calendar
          calendarApi.unselect() // clear date selection
          calendarApi.addEvent({
            // id: calendarId++,
            title: this.search,
            start: this.calendarInfo.startStr,
            end: this.calendarInfo.endStr,
            allDay: this.calendarInfo.allDay
          });
          console.log(2);
        }
        this.systemStore.hideOverlay();
      }
    },
    validate() {
      let valid = true;

      //  등록된 환자가 아니고 신규 환자일 때,
      if(this.registPatient === null){
        if (this.search.trim().length === 0) {
          valid = false;
          searchName.value.error = true;
        }
        if (this.searchBirthDate.trim().length === 0) {
          valid = false;
          searchBirthDate.value.error = true;
        }
        if (this.searchCellPhone.trim().length === 0) {
          valid = false;
          searchCellPhone.value.error = true;
        }
      }
      //  등록된 환자인 경우
      else{

      }
      return valid
    }

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

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

};
</script>

<style>
    .autocomplete {
      position: relative;
    }
  
    .autocomplete-results {
      padding: 0;
      margin: 0;
      border: 1px solid #eeeeee;
      height: 120px;
      overflow: auto;
    }
  
    .autocomplete-result {
      list-style: none;
      text-align: left;
      padding: 4px 2px;
      cursor: pointer;
    }
  
    .autocomplete-result.is-active,
    .autocomplete-result:hover {
      background-color: #4AAE9B;
      color: white;
    }
  </style>