<template>
  <v-card width="100%" :loading="processing">
    <v-toolbar>
      <v-row no-gutters class="fill-height px-6 d-flex ga-2 justify-space-between" align="center">
        <span class="font-weight-bold text-h5 text-capitalize">
          {{ prop.mode }} Vehicle <span>({{ formatVehicleType(type) }})</span>
        </span>
        <span>
          <ButtonClose @click="emit('close:all')" icon-only />
        </span>
      </v-row>
    </v-toolbar>

    <v-card-text style="max-height: 100vh; overflow-y: auto" class="pa-5 my-3">
      <span class="text-subtitle-1 w-100 font-weight-bold mb-3">General Information</span>
      <v-form ref="formRef" v-model="validForm" :disabled="processing" @click="errorMessage = ''">
        <v-row no-gutters class="pt-4">
          <v-col v-if="shouldShowField('seasonPassType')" cols="12">
            <InputLabel class="text-capitalize" title="Season Pass Type" required />
            <v-combobox v-model.trim="vehicle.seasonPassType" v-model:search="seasonPassTypeInput" :hide-no-data="false"
              @update:modelValue="onSeasonPassTypeSelected" :items="seasonPassTypeArray" :rules="[requiredRule]"
              item-title="title" item-value="value" variant="outlined" density="comfortable" persistent-hint
              small-chips>
              <template v-slot:no-data>
                <v-list-item>
                  <v-list-item-title>
                    No results matching "<strong>{{ seasonPassTypeInput }}</strong>". This value will be added as new
                    option.
                  </v-list-item-title>
                </v-list-item>
              </template>
            </v-combobox>
          </v-col>

          <v-col v-if="shouldShowField('block')" cols="12">
            <InputLabel class="text-capitalize" title="Block" required />
            <v-autocomplete v-model="vehicle.block" :items="blocksArray" autocomplete="off"
              :key="blockListDataPending ? 'block-list-pending' : 'block-list-ready'" :loading="blockListDataPending"
              item-value="value" item-title="title" @update:model-value="handleChangeBlock" density="comfortable"
              :rules="[requiredRule]" />
          </v-col>

          <v-col v-if="shouldShowField('level')" cols="12">
            <InputLabel class="text-capitalize" title="Level" required />
            <v-autocomplete v-model="vehicle.level" :items="levelsArray" autocomplete="off"
              :key="levelListDataPending ? 'level-list-pending' : 'level-list-ready'" :loading="levelListDataPending"
              density="comfortable" :disabled="!vehicle.block" @update:model-value="handleChangeLevel"
              :rules="[requiredRule]" />
          </v-col>

          <v-col v-if="shouldShowField('unit')" cols="12">
            <InputLabel class="text-capitalize" title="Unit" required />
            <v-autocomplete v-model="vehicle.unit" :items="unitsArray" autocomplete="off"
              :key="unitListDataPending ? 'unit-list-pending' : 'unit-list-ready'" :loading="unitListDataPending"
              density="comfortable" :disabled="!vehicle.level" :rules="[requiredRule]" />
          </v-col>

          <v-col v-if="shouldShowField('nric')" cols="12">
            <InputLabel class="text-capitalize" title="NRIC" required />
            <InputNRICNumber v-model="vehicle.nric" density="comfortable" :rules="[requiredRule]"
              :disabled="disablePrefilledInputs && type !== 'blocklist' && prop.mode !== 'edit'" />
          </v-col>

          <v-col v-if="shouldShowField('name')" cols="12">
            <v-row>
              <v-col cols="12">
                <InputLabel class="text-capitalize" title="Full Name" required />
                <v-text-field v-model.trim="vehicle.name" density="comfortable" :rules="[requiredRule]"
                  :disabled="disablePrefilledInputs && type !== 'blocklist' && prop.mode !== 'edit'" />
              </v-col>
            </v-row>
          </v-col>



          <v-col v-if="shouldShowField('phone')" cols="12">
            <InputLabel class="text-capitalize" title="Phone Number" required />
            <InputPhoneNumberV2 v-model="vehicle.phoneNumber" density="comfortable" :rules="[requiredRule]" />
          </v-col>

          <v-col v-if="shouldShowField('plateNumber')" cols="12">

            <template v-if="prop.mode === 'add'">
              <!-- <v-text-field v-model="vehicle.plateNumber" density="comfortable" :rules="[requiredRule]" /> -->
              <template v-for="plate in vehicle.plates" :key="plate.plateNumber">
                <InputLabel class="text-capitalize" title="Existing Vehicle Numbers" required />
                <v-text-field v-model="plate.plateNumber" density="comfortable" :rules="[requiredRule]"
                  class="mb-2 class-readonly" readonly>
                  <template #append-inner>
                    <v-chip size="small" class="ma-0" :color="formatVehicleStatus(plate?.status)?.color as string">{{
                      formatVehicleStatus(plate?.status)?.label }}</v-chip>
                  </template>
                </v-text-field>
              </template>

              <InputLabel class="text-capitalize" title="New Vehicle Numbers" required />
              <template v-for="(plate, index) in newPlateNumbers" :key="index">
                <v-row class="" :class="`${index === newPlateNumbers.length - 1 ? 'mb-1' : 'mb-5'}`" no-gutters>
                  <v-col :cols="newPlateNumbers.length > 1 ? '11' : '12'">
                    <InputVehicleNumber v-model="newPlateNumbers[index]" density="comfortable"
                      placeholder="New Vehicle Number" :rules="[requiredRule]" />
                  </v-col>

                  <v-col :cols="newPlateNumbers.length > 1 ? '1' : '0'" class="d-flex align-start">
                    <v-btn icon="mdi-delete-outline" variant="text" color="error" v-if="newPlateNumbers.length > 1"
                      @click="removePlate(index)" />
                  </v-col>
                </v-row>

                <v-btn prepend-icon="mdi-plus" variant="outlined" class="text-none" @click="addPlate">
                  Add Plate
                </v-btn>
              </template>
            </template>

            <template v-else-if="prop.mode === 'edit'">
              <InputLabel class="text-capitalize" title="Vehicle Number" required />
              <InputVehicleNumber v-model="vehicle.plateNumber" density="comfortable" :rules="[requiredRule]" />
            </template>
          </v-col>

          <v-col v-if="shouldShowField('remarks')" cols="12">
            <InputLabel class="text-capitalize" title="Remarks" />
            <v-textarea v-model="vehicle.remarks" density="comfortable" :rows="3" no-resize />
          </v-col>

          <v-col v-if="shouldShowField('start')" cols="12">
            <v-expand-transition v-if="showSubscriptionDateOptions">
              <v-row no-gutters>
                <!-- <v-row dense justify="space-between">
                  <template v-for="option in subscriptionOptions" :key="option.value">
                    <v-col cols="4">
                      <v-btn :text="option.label" class="text-capitalize" min-width="120" :ripple="false"
                        :class="[option.value === selectedSubscriptionDuration ? 'button-outline-class' : '']"
                        @click="selectedSubscriptionDuration = option.value" />
                    </v-col>

                  </template>
                </v-row> -->

                <v-row no-gutters class="mt-5">
                  <v-col cols="12">
                    <InputLabel class="text-capitalize" title="Start Date" required />
                    <InputDateTimePicker ref="startDateRef" v-model="vehicle.start" :rules="[validStartDateRule]" />
                  </v-col>

                  <v-col cols="12">
                    <InputLabel class="text-capitalize" title="Expiry Date" required />
                    <InputDateTimePicker ref="expiryDateRef" v-model="vehicle.end" :rules="[validExpiryDateRule]" />
                  </v-col>
                </v-row>
              </v-row>


            </v-expand-transition>

            <v-col cols="12" :class="[showSubscriptionDateOptions && 'mt-5']">
              <v-row justify="center">
                <v-col cols="6">
                  <v-btn block color="primary" variant="text" class="text-none font-weight-bold"
                    :text="showSubscriptionDateOptions ? 'Hide Subscription Options' : 'Show Subscription Options'"
                    @click="showSubscriptionDateOptions = !showSubscriptionDateOptions"></v-btn>
                </v-col>
              </v-row>
            </v-col>
          </v-col>

          <v-col cols="12">
            <v-row no-gutters>
              <v-col cols="12" class="text-center">
                <span class="text-none text-subtitle-2 font-weight-medium text-error">
                  {{ message }}
                </span>
              </v-col>
            </v-row>
          </v-col>
        </v-row>
      </v-form>
    </v-card-text>
    <v-row no-gutters class="w-100" v-if="errorMessage">
      <p class="text-error w-100 text-center text-subtitle-2">{{ errorMessage }}</p>
    </v-row>
    <v-toolbar density="compact">
      <v-row no-gutters>
        <v-col cols="6">
          <v-btn v-if="prop.mode === 'add'" tile block variant="text" class="text-none" size="48" @click="back"
            text="Back to Selection" />
          <v-btn v-else tile block variant="text" class="text-none" size="48" @click="close" text="Close" />
        </v-col>
        <v-col cols="6">
          <v-btn tile block variant="flat" color="black" class="text-none" size="48"
            :disabled="!validForm || processing" @click="submit" :text="prop.mode == 'add' ? 'Submit' : 'Update'" />
        </v-col>
      </v-row>
    </v-toolbar>

    <v-dialog v-model="showMatchingPeopleDialog" max-width="700" persistent>
      <v-card :loading="checkingUnit">
        <v-toolbar>
          <v-toolbar-title>
            <v-row no-gutters class="d-flex align-center justify-space-between">
              <span class="font-weight-bold">
                Matching Records for "{{ searchUnitName ?? "-" }}"
              </span>
              <span>
                <v-btn icon="mdi-close" variant="text" @click="handleCloseMatchDialog" />
              </span>
            </v-row>
          </v-toolbar-title>
        </v-toolbar>

        <v-card-text max-height="400" style="overflow-y: auto">

          <v-list lines="three">
            <v-list-item v-if="matchingPeople.length > 0 || checkingUnit" v-for="v in matchingPeople" :key="v._id"
              class="cursor-pointer">
              <v-list-item-title>
                {{ v.name }}
              </v-list-item-title>

              <v-list-item-subtitle>
                NRIC: {{ v.nric || "-" }}
              </v-list-item-subtitle>

              <div class="mt-1">
                <v-chip v-for="p in v.plates" :key="p?.plateNumber" size="small" class="mr-1">
                  {{ p?.plateNumber }}
                </v-chip>
              </div>

              <template #append>
                <v-btn variant="flat" color="primary" @click="selectPeopleRecord(v)">Select</v-btn>
              </template>

            </v-list-item>
            <v-empty-state v-else icon="mdi-account-off" title="No matching records found"
              subtitle="The NRIC you entered does not match any existing records.">
              <template #actions>
                <v-btn variant="flat" color="primary" @click="showMatchingPeopleDialog = false">Close</v-btn>
              </template>
            </v-empty-state>
          </v-list>

        </v-card-text>
      </v-card>
    </v-dialog>

  </v-card>
</template>

<script setup lang="ts">



const prop = defineProps({
  type: {
    type: String as PropType<TVehicleType | 'seasonpass'>,
    required: true
  },
  org: {
    type: String,
    required: true
  },
  site: {
    type: String,
    required: true
  },
  mode: {
    type: String as PropType<'add' | 'edit'>,
    default: 'add'
  },
  vehicleData: {
    type: Object as PropType<Partial<TVehicle> | null>,
    default: null
  },
  plateNumberId: {
    type: String,
    default: ''
  }
});

const { requiredRule, formatDateISO8601, debounce } = useUtils();
const { addVehicle, getCustomSeasonPassTypes, updateVehicle, formatVehicleStatus } = useVehicle();
const { getSiteById, getSiteLevels, getSiteUnits } = useSiteSettings();
const { findPersonByNRICMultipleResult, getPeopleByUnit } = usePeople();
const { getBlocksSelection, getLevelsSelection, getUnitSelection } = useBuilding();

const emit = defineEmits(['back', 'select', 'done', 'error', 'close', 'close:all']);


const vehicle = reactive<Omit<ExceptPartial<TVehicle>, 'type'> & { type: TVehicleType | 'seasonpass' }>({
  plates: [],
  type: prop.type,
  category: "resident",
  name: '',
  phoneNumber: '',
  block: '',
  level: '',
  unit: '',
  nric: '',
  remarks: '',
  seasonPassType: '',
  start: '',
  end: '',
  site: prop.site,
  org: prop.org,
  _id: '',
  peopleId: '',
  plateNumber: "",
});

const newPlateNumbers = ref<string[]>(['']);
const disablePrefilledInputs = ref(true);

const blocksArray = ref<TDefaultOptionObj[]>([]);
const levelsArray = ref<TDefaultOptionObj[]>([]);
const unitsArray = ref<TDefaultOptionObj[]>([]);
const seasonPassTypeArray = ref<{ title: string, value: string }[]>([]);

const matchingPeople = ref<Partial<TPeople>[]>([]);
const showMatchingPeopleDialog = ref(false);
const prefillingRecords = ref(false);
const checkingNRIC = ref(false);
const checkingUnit = ref(false);

const defaultSeasonPassTypeArray = computed(() => {
  return [
    'Resident Season Pass',
    'Tenant/Leaseholder Pass',
    'VIP/Preferred Parking Pass',
    'Visitor Season Pass',
    'Staff & Service Provider Pass',
    'Business Tenant Pass',
  ].map((item) => ({
    title: item,
    value: item
  }))
});


const typeFieldMap: Record<TVehicleType | 'seasonpass', string[]> = {
  seasonpass: ['seasonPassType', 'name', 'phone', 'plateNumber', 'block', 'level', 'unit', 'start', 'end'],
  blocklist: ['name', 'nric', 'phone', 'plateNumber', 'remarks'],
  whitelist: ['name', 'nric', 'phone', 'plateNumber', 'block', 'level', 'unit']
};

const shouldShowField = (fieldKey: string): boolean => {
  const visibleFields = typeFieldMap[prop.type as TVehicleType];
  return visibleFields?.includes(fieldKey);
};


const searchUnitName = computed(() => {
  return unitsArray.value.find(u => u.value === vehicle.unit)?.title || vehicle.unit;
})


const validForm = ref(false);
const seasonPassTypeInput = ref('')
const formRef = ref<HTMLFormElement | null>(null);
const startDateRef = ref<HTMLInputElement | null>(null)
const expiryDateRef = ref<HTMLInputElement | null>(null)
const processing = ref(false);
const message = ref('');
const selectedSubscriptionDuration = ref<string | null>('custom')
const showSubscriptionDateOptions = ref(false)
const errorMessage = ref('');


// fetch existing vehicle data if in edit mode
if (prop.vehicleData) {
  const existingVehicleData = JSON.parse(JSON.stringify(prop.vehicleData || {}));
  Object.assign(vehicle, existingVehicleData);
}



const {
  data: blocksListData,
  refresh: refreshBlockListData,
  status: blocksListStatus,
  pending: blockListDataPending,
} = useAsyncData(`vehicle-fetch-block-list-data-${prop.site}`, () =>
  getBlocksSelection({ siteId: prop.site }), { watch: [() => prop.site], deep: true }
);


const {
  data: levelsData,
  refresh: refreshLevelsData,
  status: levelsStatus,
  pending: levelListDataPending,
} = useAsyncData(
  `vehicle-fetch-levels-data-${prop.site}-${vehicle.block}`,
  async () => {
    if (!vehicle.block) return Promise.resolve(null);
    // return await getSiteWithLevels(prop.site, { block: Number(vehicle.block) });
    return await getLevelsSelection({ siteId: prop.site, blockId: vehicle.block._id ? vehicle.block._id : vehicle.block });
  }, { watch: [() => vehicle.block], deep: true }
);

const {
  data: unitsData,
  refresh: refreshUnitsData,
  status: unitsStatus,
  pending: unitListDataPending,
} = useAsyncData(
  `vehicle-fetch-units-data-${prop.site}-${vehicle.level}`,
  async () => {
    if (!vehicle.level) return Promise.resolve(null);
    return await getUnitSelection({ siteId: prop.site, block: vehicle.block._id ? vehicle.block._id : vehicle.block, level: vehicle.level._id ? vehicle.level._id : vehicle.level });
  }, { watch: [() => vehicle.level], deep: true }
);


const { data: seasonPassTypeData, refresh: refreshSeasonPassTypeData } = useLazyAsyncData(
  `vehicle-fetch-season-pass-type-data-${prop.site}`,
  async () => await getCustomSeasonPassTypes(prop.site));


watch(
  [blocksListData],
  () => {
    if (blocksListStatus.value === 'pending') {
      blocksArray.value = [];
      return;
    }

    const arr = Array.isArray(blocksListData.value?.data) ? blocksListData.value?.data : [];
    blocksArray.value = arr.map((block: any) => ({
      title: block.name,
      value: block._id,
    }));
  },
  { immediate: true, deep: true }
)

watch([levelsData], () => {
  if (levelsStatus.value === 'pending') {
    levelsArray.value = [];
    return;
  }

  const arr = Array.isArray(levelsData.value?.data) ? levelsData.value?.data : [];
  const mappedLevels = arr.map((level: any) => ({
    title: level.name,
    value: level._id,
  }));
  levelsArray.value = mappedLevels;
}, { immediate: true, deep: true })

watch(
  unitsData,
  (newVal: any) => {
    if (newVal && Array.isArray(newVal)) {
      const arr = newVal || [];
      unitsArray.value = arr?.map((unit: any) => ({
        title: unit?.name,
        value: unit?._id
      }));
    } else {
      unitsArray.value = [];
    }
  }, { immediate: true });


watch(
  seasonPassTypeData,
  (newVal) => {
    if (Array.isArray(newVal)) {
      const filteredArr = newVal.filter((item: any) => item.title && item.value);
      seasonPassTypeArray.value = [...defaultSeasonPassTypeArray.value, ...filteredArr];
    } else {
      seasonPassTypeArray.value = defaultSeasonPassTypeArray.value;
    }
  }, { immediate: true });




const subscriptionOptions = computed(() => {
  return [
    { label: 'Custom', value: 'custom' },
    { label: '1 Week', value: '1week' },
    { label: '2 Weeks', value: '2weeks' },
    { label: '3 Weeks', value: '3weeks' },
    { label: '4 Weeks', value: '4weeks' },
    { label: '5 Weeks', value: '5weeks' },
  ];
})

function handleChangeBlock(value: any) {
  vehicle.level = '';
  vehicle.unit = '';
  refreshLevelsData();
}

function handleChangeLevel(value: any) {
  vehicle.unit = '';
  refreshUnitsData();
}

function addPlate() {
  newPlateNumbers.value.push('');
}


function removePlate(index: number) {
  newPlateNumbers.value.splice(index, 1);
}

function back() {
  emit("back");
  message.value = '';
  showSubscriptionDateOptions.value = false;
  selectedSubscriptionDuration.value = null;
}

function close() {
  emit("close");
  message.value = '';
  showSubscriptionDateOptions.value = false;
  selectedSubscriptionDuration.value = null;
}

function formatVehicleType(type: TVehicleType | 'seasonpass'): string {
  switch (type) {
    case 'whitelist':
      return 'Whitelist';
    case 'blocklist':
      return 'Blocklist';

    case 'seasonpass':
      return 'Season Pass';
    default:
      return '';
  }
}

function onSeasonPassTypeSelected(val: string | { title: string, value: string }) {
  vehicle.seasonPassType = typeof val === 'object' ? val?.value : val;
}


async function submit() {
  errorMessage.value = '';
  processing.value = true;
  try {
    const SPTVal = vehicle?.seasonPassType as string;
    if (SPTVal) {
      vehicle.seasonPassType = SPTVal?.charAt(0)?.toUpperCase() + SPTVal?.slice(1)?.toLowerCase();
    }


    const { plateNumber, type, category, name, phoneNumber, block, level, unit, nric, remarks, seasonPassType, start, end, site, org, peopleId } = vehicle

    let payload: Partial<TVehiclePayload> = {
      name,
      phoneNumber,
      type: type === 'seasonpass' ? 'whitelist' : type, // season pass will be created as whitelist type in backend with additional seasonPassType field,
      nric,
      peopleId
    };

    if (prop.mode === 'add') {
      payload = {
        ...payload,
        category,
        site,
        org,
        plateNumber: newPlateNumbers.value
      }
    }

    if (prop.mode === 'edit' && prop.plateNumberId) {
      payload = {
        ...payload,
        site: prop.site,
        plateNumber
      }
    }

    if (vehicle.type === 'whitelist') {
      payload = {
        ...payload,
        block,
        level,
        unit,
      };
    } else if (vehicle.type === 'seasonpass') {
      payload = {
        ...payload,
        seasonPassType,
        block,
        level,
        unit,
        start,
        end
      };
    } else if (vehicle.type === 'blocklist') {
      payload = {
        ...payload,
        remarks,
      };
    }

    if (prop.mode === 'add') {
      await addVehicle(payload);
    } else if (prop.mode === 'edit') {
      const plateNumberId = prop.plateNumberId as string;
      await updateVehicle(plateNumberId, payload);
    }
    emit("done");


  } catch (error: any) {
    const err = error?.data?.message
    errorMessage.value = err || `Failed to ${prop.mode === 'add' ? 'add' : 'update'} vehicle. Please try again.`;
  } finally {
    processing.value = false;
  }
}

// const showComponent = (value: TVehicleType[]) => {
//   return value.includes(prop.type);

// }

watch(selectedSubscriptionDuration, (duration) => {


  const dateNowISO = formatDateISO8601(new Date())
  const weeksLaterISO = (week: number) => {
    const now = new Date()
    const dateWeekLater = new Date(now.getTime() + (week * 7) * 24 * 60 * 60 * 1000)
    return formatDateISO8601(dateWeekLater)
  }

  if (duration === 'custom') {
    vehicle.start = '';
    vehicle.end = '';
  } else if (duration === '1week') {
    vehicle.start = dateNowISO
    vehicle.end = weeksLaterISO(1)
  } else if (duration === '2weeks') {
    vehicle.start = dateNowISO
    vehicle.end = weeksLaterISO(2)
  } else if (duration === '3weeks') {
    vehicle.start = dateNowISO
    vehicle.end = weeksLaterISO(3)
  } else if (duration === '4weeks') {
    vehicle.start = dateNowISO
    vehicle.end = weeksLaterISO(4)
  } else if (duration === '5weeks') {
    vehicle.start = dateNowISO
    vehicle.end = weeksLaterISO(5)
  }
})

function validStartDateRule(value: string) {
  const expiryDateISO = vehicle.end;
  if (!value && expiryDateISO) {
    return 'Start Date is required';
  }

  return true;
}

function validExpiryDateRule() {
  const startDateISO = vehicle.start;
  const endDateISO = vehicle.end;

  if (!endDateISO && startDateISO) {
    return 'Expiry Date is required';
  }

  if (endDateISO && startDateISO) {
    const expiry = new Date(endDateISO);
    const start = new Date(startDateISO as string);
    return expiry > start || 'Expiry date must be later than start date';
  }

  return true;
}

watch([() => vehicle.end, () => vehicle.start], () => {
  (expiryDateRef.value as any)?.validate();
  (startDateRef.value as any)?.validate();
});


function selectPeopleRecord(record: TPeople) {

  vehicle.name = record.name;
  vehicle.phoneNumber = record.contact;
  vehicle.nric = record.nric;
  vehicle.plates = record.plates || [];
  disablePrefilledInputs.value = true;
  showMatchingPeopleDialog.value = false;
  vehicle.peopleId = record._id || '';
}


// async function checkNRIC() {
//   if (!vehicle.nric || vehicle.nric.length < 5) return;

//   checkingNRIC.value = true;
//   showMatchingPeopleDialog.value = true;
//   // Lock editable fields while we verify if this NRIC has existing records.
//   disablePrefilledInputs.value = true;
//   try {
//     const res = await findPersonByNRICMultipleResult(vehicle.nric, prop.site) as { items: TPeople[] } | null;

//     if (res?.items && res.items.length > 0) {
//       matchingPeople.value = res.items || []
//       // Force selection from matched records.
//       disablePrefilledInputs.value = true;
//     } else {
//       matchingPeople.value = [];
//       // No match found, allow manual input.
//       disablePrefilledInputs.value = false;
//     }


//   } catch (error) {
//     console.error("NRIC search failed:", error);
//     disablePrefilledInputs.value = false;
//   } finally {
//     checkingNRIC.value = false;
//   }
// }

// const debounceedCheckNRIC = debounce(checkNRIC, 500);



async function checkPeopleById() {
  if (!vehicle.unit || prop.mode === 'edit' || prefillingRecords.value) return;

  checkingUnit.value = true;
  showMatchingPeopleDialog.value = true;
  // Lock editable fields while we verify if this NRIC has existing records.
  disablePrefilledInputs.value = true;
  try {
    const res = await getPeopleByUnit(vehicle.unit, { status: 'active', type: 'resident,tenant' }) as TPeople[] | null;

    if (Array.isArray(res) && res.length > 0) {
      matchingPeople.value = res || []
      // Force selection from matched records.
      disablePrefilledInputs.value = true;
    } else {
      matchingPeople.value = [];
      // No match found, allow manual input.
      disablePrefilledInputs.value = false;
    }


  } catch (error) {
    console.error("Unit search failed:", error);
    // disablePrefilledInputs.value = false;
  } finally {
    checkingUnit.value = false;
  }
}

const debounceedCheckUnit = debounce(checkPeopleById, 500);

watch(
  () => vehicle.unit,
  async (newUnit) => {
    if (prefillingRecords.value) return;

    resetVehicleDetails();
    matchingPeople.value = [];
    if (!newUnit) return;

    debounceedCheckUnit();
  }
);


const resetVehicleDetails = () => {
  vehicle.name = '';
  vehicle.phoneNumber = '';
  vehicle.plates = [];
  vehicle.nric = '';
  vehicle.peopleId = '';
}


function handleCloseMatchDialog() {
  showMatchingPeopleDialog.value = false;
  if (matchingPeople.value.length > 0) {
    vehicle.unit = null
  }
}

onMounted(() => {
  setTimeout(() => {
    console.log("VehicleForm mounted with props:", prop);
    if (prop.mode === 'edit' && prop.vehicleData) {
      // In edit mode, we only want to check for matching people records if there is a pre-filled unit value. If there is no unit value, we can assume that this vehicle record is not linked to any existing people record and skip the check.
      vehicle.seasonPassType = prop.vehicleData.seasonPassType || '';
      vehicle.end = prop.vehicleData.end || '';
      vehicle.start = prop.vehicleData.start || '';
      vehicle.plateNumber = prop.vehicleData.plateNumber
      vehicle.peopleId = prop.vehicleData.peopleId || '';
      vehicle.block = prop.vehicleData.block || null;

      if (prop.type === "seasonpass") {
        showSubscriptionDateOptions.value = true;
      }
    }
  }, 300);

  if (prop.mode === 'add' && prop.type !== 'blocklist') {
    // For add mode, we want to check for matching people records if the type is not blocklist, as blocklist records are typically not linked to people records.
    prefillingRecords.value = true;
    vehicle.block = prop.vehicleData?.block?._id ? prop.vehicleData?.block?._id : '';
    vehicle.level = prop.vehicleData?.level?._id ? prop.vehicleData?.level?._id : '';
    vehicle.unit = prop.vehicleData?.unit?._id ? prop.vehicleData?.unit?._id : '';
  }

  nextTick(() => {
    prefillingRecords.value = false;
  })
})


</script>
<style scoped>
.button-outline-class {
  border: 1px solid rgba(var(--v-theme-primary));
}

.class-readonly {
  pointer-events: none;
}
</style>
