<script setup>
import { PerfectScrollbar } from 'vue3-perfect-scrollbar';
import { VForm } from 'vuetify/components/VForm';
import { useStore } from 'vuex';
const store = useStore()
const props = defineProps({
  isDrawerOpen: {
    type: Boolean,
    required: true,
  },
  userData: {
    type: Object,
    required: true,
  }
})
const states = ref([
    { name: 'Alabama', abbreviation: 'AL' },
    { name: 'Alaska', abbreviation: 'AK' },
    { name: 'Arizona', abbreviation: 'AZ' },
    { name: 'Arkansas', abbreviation: 'AR' },
    { name: 'Howland Island', abbreviation: 'UM-84' },
    { name: 'Delaware', abbreviation: 'DE' },
    { name: 'Maryland', abbreviation: 'MD' },
    { name: 'Baker Island', abbreviation: 'UM-81' },
    { name: 'Kingman Reef', abbreviation: 'UM-89' },
    { name: 'New Hampshire', abbreviation: 'NH' },
    { name: 'Wake Island', abbreviation: 'UM-79' },
    { name: 'Kansas', abbreviation: 'KS' },
    { name: 'Texas', abbreviation: 'TX' },
    { name: 'Nebraska', abbreviation: 'NE' },
    { name: 'Vermont', abbreviation: 'VT' },
    { name: 'Jarvis Island', abbreviation: 'UM-86' },
    { name: 'Hawaii', abbreviation: 'HI' },
    { name: 'Guam', abbreviation: 'GU' },
    { name: 'United States Virgin Islands', abbreviation: 'VI' },
    { name: 'Utah', abbreviation: 'UT' },
    { name: 'Oregon', abbreviation: 'OR' },
    { name: 'California', abbreviation: 'CA' },
    { name: 'New Jersey', abbreviation: 'NJ' },
    { name: 'North Dakota', abbreviation: 'ND' },
    { name: 'Kentucky', abbreviation: 'KY' },
    { name: 'Minnesota', abbreviation: 'MN' },
    { name: 'Oklahoma', abbreviation: 'OK' },
    { name: 'Pennsylvania', abbreviation: 'PA' },
    { name: 'New Mexico', abbreviation: 'NM' },
    { name: 'American Samoa', abbreviation: 'AS' },
    { name: 'Illinois', abbreviation: 'IL' },
    { name: 'Michigan', abbreviation: 'MI' },
    { name: 'Virginia', abbreviation: 'VA' },
    { name: 'Johnston Atoll', abbreviation: 'UM-67' },
    { name: 'West Virginia', abbreviation: 'WV' },
    { name: 'Mississippi', abbreviation: 'MS' },
    { name: 'Northern Mariana Islands', abbreviation: 'MP' },
    { name: 'United States Minor Outlying Islands', abbreviation: 'UM' },
    { name: 'Massachusetts', abbreviation: 'MA' },
    { name: 'Connecticut', abbreviation: 'CT' },
    { name: 'Florida', abbreviation: 'FL' },
    { name: 'District of Columbia', abbreviation: 'DC' },
    { name: 'Midway Atoll', abbreviation: 'UM-71' },
    { name: 'Navassa Island', abbreviation: 'UM-76' },
    { name: 'Indiana', abbreviation: 'IN' },
    { name: 'Wisconsin', abbreviation: 'WI' },
    { name: 'Wyoming', abbreviation: 'WY' },
    { name: 'South Carolina', abbreviation: 'SC' },
    { name: 'South Dakota', abbreviation: 'SD' },
    { name: 'Montana', abbreviation: 'MT' },
    { name: 'North Carolina', abbreviation: 'NC' },
    { name: 'Palmyra Atoll', abbreviation: 'UM-95' },
    { name: 'Puerto Rico', abbreviation: 'PR' },
    { name: 'Colorado', abbreviation: 'CO' },
    { name: 'Missouri', abbreviation: 'MO' },
    { name: 'New York', abbreviation: 'NY' },
    { name: 'Maine', abbreviation: 'ME' },
    { name: 'Tennessee', abbreviation: 'TN' },
    { name: 'Georgia', abbreviation: 'GA' },
    { name: 'Louisiana', abbreviation: 'LA' },
    { name: 'Nevada', abbreviation: 'NV' },
    { name: 'Iowa', abbreviation: 'IA' },
    { name: 'Idaho', abbreviation: 'ID' },
    { name: 'Rhode Island', abbreviation: 'RI' },
    { name: 'Washington', abbreviation: 'WA' },
    { name: 'Ohio', abbreviation: 'OH' },
    // ... (add the rest of the states)
]);
const sortedStates = computed(() => {
    return states.value.slice().sort((a, b) => {
        return a.name.localeCompare(b.name);
    });
});
const isPasswordVisible = ref(false)
const emit = defineEmits(['update:isDrawerOpen','patientAdded'])
const formatPhoneNumber = () => {

  // Remove non-numeric characters from the input
  const numericValue = phone_no.value.replace(/\D/g, '');

  // Apply formatting logic
  if (numericValue.length <= 10) {
     phone_no.value = numericValue.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
  } else {
    // Limit the input to a maximum of 14 characters
    const truncatedValue = numericValue.slice(0, 10);
     phone_no.value= truncatedValue.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
  }
};
const handleDrawerModelValueUpdate = val => {
  emit('update:isDrawerOpen', val)
}
const genders = ref([
  { name: 'Male', abbreviation: 'Male' },
  { name: 'Female', abbreviation: 'Female' },
  { name: 'Other', abbreviation: 'Other' },
]);
const refVForm = ref()
const first_name = ref()
const last_name = ref()
const email = ref()
const addressLine1 = ref()
const city = ref()
const state = ref()
const zip_code = ref()
const country = ref()
const phone_no = ref()
const dob = ref()
const gender = ref()
const password = ref()
const itemId = ref()

const isBillingAddress = ref(false)
const getCurrentDate = () => {
  const today = new Date();
  console.log("today", today);
  const year = today.getFullYear();
  let month = today.getMonth() + 1;
  let day = today.getDate();

  // Format the date to match the input type="date" format
  month = month < 10 ? `0${month}` : month;
  day = day < 10 ? `0${day}` : day;

  return `${month}-${day}-${year}`;
};
const calculateAge = (dateOfBirth) => {
  const today = new Date();
  const birthDate = new Date(dateOfBirth);
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();

  if (
    monthDiff < 0 ||
    (monthDiff === 0 && today.getDate() < birthDate.getDate())
  ) {
    age--;
  }

  return age;
};
const onSubmit = async () => {
  const { valid } = await refVForm.value.validate()
  if (valid) {
    if (calculateAge(dob.value) >= 18) {
      await store.dispatch('patientUpdate', {
        id:itemId.value,
        first_name: first_name.value,
        last_name: last_name.value,
        email: email.value,
        password: password.value,
        phone_no: phone_no.value,
        dob: dob.value,
        address: addressLine1.value,
        city: city.value,
        state: state.value,
        zip_code:zip_code.value,
        country: country.value,
        gender: gender.value
      })
    } else {
      store.dispatch('updateErrorMessage', 'Patient must be 18+')
    }
    if (!store.getters.getErrorMsg) {
      emit('patientAdded', 'success')
        first_name.value = null
          last_name.value = null
          email.value = null
          password.value = null
          phone_no.value = null
          dob.value = null
          addressLine1.value = null
          city.value = null
          state.value = null
          country.value = null
          zip_code.value=null
    }
   emit('update:isDrawerOpen', false)
  }
}
  
const getPatientList = computed(async () => {
  if (props.userData) {
      itemId.value=props.userData.id
      first_name.value = props.userData.first_name
          last_name.value = props.userData.last_name
          email.value = props.userData.email
          password.value = props.userData.password
          phone_no.value = props.userData.phone_no
          dob.value = props.userData.dob
          addressLine1.value = props.userData.shipping_address
          city.value = props.userData.shipping_city
          state.value = props.userData.shipping_state
          country.value = props.userData.shipping_country
          zip_code.value = props.userData.shipping_zipcode
          gender.value= props.userData.gender
  }
        
});
const resetForm = () => {
  refVForm.value?.reset()
  emit('update:isDrawerOpen', false)
}
</script>

<template>
  <VNavigationDrawer
    :model-value="props.isDrawerOpen"
    temporary
    location="end"
    width="800"
    @update:model-value="handleDrawerModelValueUpdate"
  >
    <!-- 👉 Header -->
    <AppDrawerHeaderSection
      title="Edit Patient"
      @cancel="$emit('update:isDrawerOpen', false)"
    />
    <VDivider />

    <VCard flat>
      <PerfectScrollbar
        :options="{ wheelPropagation: false }"
        class="h-100"
      >
        <VCardText style="block-size: calc(100vh - 5rem);" v-if="getPatientList">
          <VForm
            ref="refVForm"
            @submit.prevent=""

          >
            <VRow>
              <VCol cols="12" md="12">
                <div class="text-body-1 font-weight-medium text-high-emphasis">
                  Basic Information
                </div>
              </VCol>

              <VCol cols="12" md="6">
                <VTextField
                  v-model="first_name"
                  label="First Name"
                  :rules="[requiredValidator]"
                  placeholder="First Name"
                />
              </VCol>
              <VCol cols="12" md="6">
                    <VTextField
                      v-model="last_name"
                      label="Last Name"
                      :rules="[requiredValidator]"
                      placeholder="Last Name"
                    />
                  </VCol>
              <VCol cols="12" md="6">
                <VTextField
                  v-model="email"
                  label="Email Address"
                  :rules="[requiredValidator, emailValidator]"
                  placeholder="johndoe@email.com"
                  readonly
                  
                />
              </VCol>
              <VCol
                  cols="12"
                  md="6"
                >
                  <VTextField
                    v-model="password"
                    label="Password"
                    placeholder="············"
                    :type="isPasswordVisible ? 'text' : 'password'"
                    :append-inner-icon="isPasswordVisible ? 'ri-eye-off-line' : 'ri-eye-line'"
                    @click:append-inner="isPasswordVisible = !isPasswordVisible"
                    
                  />
                </VCol>

              <VCol cols="12" md="6">
                  <VTextField v-model="phone_no" label="Phone Number" pattern="^\(\d{3}\) \d{3}-\d{4}$"
                  :rules="[requiredPhone, validUSAPhone]" placeholder="i.e. (000) 000-0000"
                  @input="formatPhoneNumber" max="14" density="comfortable" />
              </VCol>
              <VCol cols="12" md="6">
                <v-select v-model="gender" label="Gender" :items="genders" item-title="name" item-value="abbreviation"
                  :rules="[requiredValidator]"  density="comfortable">
                </v-select>
              </VCol>
               <VCol cols="12" md="6">
              <AppDateTimePicker
                v-model="dob"
                label="Date Of Birth"
                placeholder="Date Of Birth"
                format="MM-dd-yyyy"
              :config="{  dateFormat: 'Y-m-d' }"
                :max="getCurrentDate()"
                :rules="[requiredValidator]"
              />
                
              </VCol>
              <VCol cols="12">
                <div class="text-body-1 font-weight-medium text-high-emphasis">
                  Shipping Information
                </div>
              </VCol>

              <VCol cols="12">
                <VTextField
                  v-model="addressLine1"
                  label="Address Line 1*"
                  :rules="[requiredValidator]"
                  placeholder="45, Rocker Terrace"
                />
              </VCol>


              <VCol  cols="12" md="6">
                <VTextField
                  v-model="city"
                  label="City*"
                  :rules="[requiredValidator]"
                  placeholder="New York"
                />
              </VCol>

              <VCol cols="12" md="6">
               
                <VAutocomplete
                v-model="state"
                      label="States"
                     :items="sortedStates"
                     item-title="name" item-value="abbreviation"
                      placeholder="Select State"
                      :rules="[requiredState]"
                    />
              </VCol>

              <VCol  cols="12" md="6">
                <VTextField
                  v-model="zip_code"
                  label="Zip Code*"
                  type="number"
                  :rules="[requiredValidator]"
                  placeholder="982347"
                />
              </VCol>

              <VCol cols="12" md="6">
                <VSelect
                  v-model="country"
                  placeholder="United States"
                  :rules="[requiredValidator]"
                  label="Country"
                  :items="['United States']"
                />
              </VCol>

             

              <VCol cols="12">
                <div class="d-flex justify-start">
                  <VBtn
                    type="submit"
                    color="primary"
                    class="me-4"
                    @click="onSubmit"
                  >
                    Save
                  </VBtn>
                  <VBtn
                    color="error"
                    variant="outlined"
                    @click="resetForm"
                  >
                    Discard
                  </VBtn>
                </div>
              </VCol>
            </VRow>
          </VForm>
        </VCardText>
      </PerfectScrollbar>
    </VCard>
  </VNavigationDrawer>
</template>

<style lang="scss">
.v-navigation-drawer__content {
  overflow-y: hidden !important;
}
</style>
