<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 isAddCustomerDrawerOpen = ref(false)
const isEditCustomerDrawerOpen = ref(false)

const editDialog = ref(false)
const addDialog = ref(false)
const deleteDialog = ref(false)
const search = ref('')
const refVForm = ref(null)
const refVFormAdd = ref(null)
const selectDropdown = ref(false)
const selectdataList = ref(null)
const defaultItem = ref({
  id: -1,
  title: '',
  slug: '',
  list_one_title: '',
  list_sub_title: '',
  list_two_title: '',
  price: '',
  currency:""
})
const itemId = ref()
const requiredImageValidator = (value) => !!value || 'Please select an image file.'
    const requiredExcelValidator = (value) => !!value || 'Please select an Excel file.'
const imageFile = ref(null)
    const excelFile = ref(null)
const editedItem = ref(defaultItem.value)
const editedIndex = ref(-1)
const medicineList = ref([])
const isLoading = ref(false)
const currencySign = ref('$');
const imageBase64 = ref(null)
    const excelBase64 = ref(null)
const currencies = ref([
  { code: 'USD', name: 'US Dollar', sign: '$' },
  { code: 'EUR', name: 'Euro', sign: '€' },
  { code: 'GBP', name: 'British Pound', sign: '£' },
  { code: 'JPY', name: 'Japanese Yen', sign: '¥' },
])
const setCurrency = (code, sign) => {
      currencySign.value = sign;
      // You can perform additional operations with the selected currency code if needed
    };
// status options
const selectedOptions = [
  {
    text: 'Current',
    value: 1,
  },
  {
    text: 'Professional',
    value: 2,
  },
  {
    text: 'Rejected',
    value: 3,
  },
  {
    text: 'Resigned',
    value: 4,
  },
  {
    text: 'Applied',
    value: 5,
  },
]

const resolveStatusVariant = status => {
  if (status === 1)
    return {
      color: 'primary',
      text: 'Current',
    }
  else if (status === 2)
    return {
      color: 'success',
      text: 'Professional',
    }
  else if (status === 3)
    return {
      color: 'error',
      text: 'Rejected',
    }
  else if (status === 4)
    return {
      color: 'warning',
      text: 'Resigned',
    }
  else
    return {
      color: 'info',
      text: 'Applied',
    }
}

const editItem = item => {
  editedIndex.value = medicineList.value.indexOf(item)
  editedItem.value = { ...item }
  editDialog.value = true
}
const addItem = item => {
  addDialog.value = true
}
const deleteItem = item => {
  editedIndex.value = medicineList.value.indexOf(item)
  editedItem.value = { ...item }
  deleteDialog.value = true
}

const close = () => {
  editDialog.value = false
  editedIndex.value = -1
  editedItem.value = { ...defaultItem.value }
}
const closeAdd = () => {
  addDialog.value = false
}
const closeDelete = () => {
  deleteDialog.value = false
  editedIndex.value = -1
  editedItem.value = { ...defaultItem.value }
}


const subscriptionStartDate = ref();
const subscriptionRenewalDate = ref();
const getSingleProduct = computed(async () => {
  console.log("helloData",props.userData.data);
    let editData = props.userData.data;
//    console.log(editedItem.value.title)
      itemId.value=editData.id
    //   editedItem.value.id= props.userData.id
      filter.value.order    = editData.cart_id
      filter.value.item = editData.item_id
      filter.value.patient  = editData.patient_id
      subscriptionRenewalDate.value = editData.subscription_renewal_date
      subscriptionStartDate.value   = editData.subscription_start_date
      filter.value.subscription_status =    editData.subscription_status
});
const update = async () => {
  const { valid } = await refVForm.value.validate()
  console.log(valid)
  if (valid) {
    try {
            await store.dispatch('updateSubcription', {
                id:itemId.value,
                subscription_start_date: subscriptionStartDate.value,
                subscription_renewal_date: subscriptionRenewalDate.value,
                subscription_status: filter.value.subscription_status,
                cart_id: filter.value.order,
                item_id: filter.value.item,
                patient_id: filter.value.patient,
            })
        if (!store.getters.getErrorMsg) {
                        emit('addedMessage', 'success')
                            subscriptionRenewalDate.value= null
                            subscriptionStartDate.value=null
                            filter.value.subscription_status=null
                            filter.value.order=null
                            filter.value.item=null
                            filter.value.patient=null
                            emit('update:isDrawerOpen', false)
                      }
        


        } catch (error) {
          console.error(error)
        }
    
    
    close()
  }
}

const emit = defineEmits(['update:isDrawerOpen','addedMessage'])

const handleDrawerModelValueUpdate = val => {
  emit('update:isDrawerOpen', val)
}

  

const resetForm = () => {
  refVForm.value?.reset()
  emit('update:isDrawerOpen', false)
}


const filter = ref({
  patient: '',
  order:'',
  item:'',
  status:'',
  subcription_status:''
});

const useSortedPatient = () => {
  const isLoading = ref(false);
  const error = ref(null);
    const patientData = ref([]); 
    const sortedPatient = computed(() => {
    // const allOption = { id: 'all', patient_name: 'All' };
    const sortedPatientData = patientData.value.slice().sort((a, b) => {
      return a.patient_name.localeCompare(b.patient_name);
    });
    return [...sortedPatientData];
  });

  const fetchPatientData = async () => {
    isLoading.value = true;
    error.value = null;
    try {
      await store.dispatch('getAnalyticOrderFilters');
      patientData.value = store.getters.getOrderFilters || [];
      console.log('Fetched patient data:', patientData.value);
    } catch (e) {
      console.error('Error fetching patient data:', e);
      error.value = 'Failed to fetch patient data';
    } finally {
      isLoading.value = false;
    }
  };

  onBeforeMount(fetchPatientData);

  return { sortedPatient, isLoading, error, fetchPatientData };
};
const orderData = ref([]); 
const sortedOrder = computed(() => {
        console.log('sortedOrder',orderData.value);
        return orderData.value ? orderData.value: [] ;
});
const useSortedOrder = (patientId) => {
    
  const isLoading = ref(false);
  const error = ref(null);
    
    

  const fetchOrderData = async () => {
    console.log('fetchOrderData');
    isLoading.value = true;
    error.value = null;
    filter.value.order = '';
    filter.value.item = '';
    try {
      await store.dispatch('orderListByPatient',{
        patient_id: patientId,
      });
      orderData.value = store.getters.getOrderList.order_data;
      console.log('Fetched order  data:', orderData.value);
    } catch (e) {
      console.error('Error fetching order data:', e);
      error.value = 'Failed to fetch order data';
    } finally {
      isLoading.value = false;
    }
  };

  fetchOrderData();
};
 const itemData = ref([]);
const sortedItem = computed(() => {
    return itemData.value ? itemData.value: [] ;
});
const useSortedItem = (order_number) => {
    const isLoading = ref(false);
    const error = ref(null);
     
    

  const fetchItemData = async () => {
    isLoading.value = true;
    error.value = null;
    
    try {
      await store.dispatch('getItemListByOrder', {
        order_id:order_number,
      });
      itemData.value = store.getters.getItemsListByOrder.order_item;
      console.log('Fetched Item data:', itemData.value);
    } catch (e) {
      console.error('Error Item patient data:', e);
      error.value = 'Failed to fetch Item data';
    } finally {
      isLoading.value = false;
    }
  };

  fetchItemData();


};

const onPatientChange = () => {
    const patientId = filter.value.patient;
    console.log('data',patientId);
   useSortedOrder(patientId);
};
const onOrderChange = () => {
     const order_number = filter.value.order;
     
    console.log('data',order_number);
   useSortedItem(order_number);
};

const { sortedPatient, error, fetchPatientData } = useSortedPatient();

</script>

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

    <VCard flat>
      <PerfectScrollbar
        :options="{ wheelPropagation: false }"
        class="h-100"
      >
      <VCardText style="block-size: calc(100vh - 5rem);" v-if="getSingleProduct">
          <VForm
            ref="refVForm"
            @submit.prevent=""
          >
            
            
           
                 <VRow>
                     <VCol cols="12" md="12">
                    <VAutocomplete v-model="filter.patient" label="Patient" placeholder="Patient" density="comfortable"
                    :items="sortedPatient" item-title="patient_name"  :rules="[requiredValidator]"  item-value="id" :loading="isLoading" :error-messages="error"
                    @update:model-value="onPatientChange" />
                </VCol>
                <VCol cols="12" md="12">
                    <VAutocomplete v-model="filter.order" label="Orders Number" placeholder="Patient" density="comfortable"
                    :items="sortedOrder" item-title="id"  :rules="[requiredValidator]" item-value="id" :loading="isLoading" :error-messages="error"
                    @update:model-value="onOrderChange" />
                </VCol>
                <VCol cols="12" md="12">
                    <VAutocomplete v-model="filter.item" label="Order Items" placeholder="Patient" density="comfortable"
                    :items="sortedItem" item-title="product_name" item-value="id" :loading="isLoading" :error-messages="error"
                    @update:model-value="onItemChange" :rules="[requiredValidator]" />
                </VCol>

              
               <VCol cols="12" md="6">
                <AppDateTimePicker
                    v-model="subscriptionStartDate"
                    label="Subscription Start Date"
                    placeholder="Subscription Start Date"
                    :rules="[requiredValidator]"
                />
              </VCol>
              <VCol cols="12" md="6">
                <AppDateTimePicker
                    v-model="subscriptionRenewalDate"
                    label="Subscription End Date"
                    placeholder="Subscription End Date"
                    :rules="[requiredValidator]"
                />
              </VCol>
              <VCol cols="12" md="6">
                    <VSelect v-model="filter.subscription_status" label="Subcription Status" density="comfortable"
                    :items="['Pending', 'Approved']" item-title="name"  :rules="[requiredValidator]" item-value="name" :loading="isLoading" 
                     />
                </VCol>
              <!-- <VCol cols="12" md="6">
                    <VSelect v-model="filter.status" label="Status" density="comfortable"
                    :items="['Active', 'InActive']" item-title="name" :rules="[requiredValidator]" item-value="name" :loading="isLoading" 
                    />
                </VCol> -->
              <VCol cols="12">
                <div class="d-flex justify-start">
                  <VBtn
                    type="submit"
                    color="primary"
                    class="me-4"
                    @click="update"
                  >
                    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>
