<template>
    <v-row no-gutters class="w-100">
        <v-card class="w-100">
            <v-card-text>
                <v-btn block color="primary-button" :height="40" text="Scan QR Code" class="text-capitalize"
                    prepend-icon="mdi-qrcode" @click="handleScanQRPass" />
                <v-form ref="formRef" v-model="validForm" :disabled="processing" @click="errorScanPassMessage = ''">
                    <v-row no-gutters class="pt-5 ga-2">
                        <v-col cols="12">
                            <InputLabel class="text-capitalize" title="Full Name" required />
                            <v-text-field v-model.trim="memberForm.name" density="compact" hide-details
                                :rules="[requiredRule]" />
                        </v-col>

                        <v-col cols="12">
                            <InputLabel class="text-capitalize" title="NRIC" required />
                            <InputNRICNumber v-model.trim="memberForm.nric" density="compact" hide-details
                                :rules="[requiredRule]" />
                        </v-col>

                        <v-col cols="12">
                            <v-autocomplete v-model="selectedPass" v-model:search="passInput" :hide-no-data="false"
                                class="mt-3" :items="passItemsFilteredFinal" item-title="prefixAndName" item-value="_id"
                                label="Pass (optional)" variant="outlined"  density="compact" :error-messages="errorScanPassMessage"
                                persistent-hint small-chips>
                                <template v-slot:no-data>
                                    <v-list-item density="compact">
                                        <v-list-item-title v-if="passInput">
                                            No results matching "<strong>{{ passInput }}</strong>". This value will be
                                            added as new
                                            option.
                                        </v-list-item-title>
                                        <v-list-item v-else>No data available</v-list-item>
                                    </v-list-item>
                                </template>

                                <template v-slot:chip="{ props, item }">
                                    <v-chip v-if="selectedPass" v-bind="props" prepend-icon="mdi-card-bulleted-outline"
                                        :text="item.raw?.prefixAndName"></v-chip>
                                </template>
                            </v-autocomplete>
                        </v-col>

                        <v-col cols="12">
                            <InputLabel class="text-capitalize" title="Phone Number" required />
                            <InputPhoneNumberV2 v-model="memberForm.contact" density="compact" default-country="SG"
                                hide-details />
                        </v-col>

                        <v-row class="pt-3" justify="space-between">
                            <v-col cols="6">
                                <v-btn text="Add Member" :disabled="!validForm" prepend-icon="mdi-plus"
                                    color="primary-button" class="text-capitalize" @click="handleAddMember" />
                            </v-col>
                            <v-col cols="6" align="end">
                                <v-btn text="Clear Form" prepend-icon="mdi-refresh" color="primary-button"
                                    class="text-capitalize" @click.stop="handleClearForm" />
                            </v-col>
                        </v-row>
                    </v-row>
                </v-form>
            </v-card-text>
        </v-card>
        <visitor-pass-key-q-r-scanner :dialog="dialog.scanQRCode" v-model:scannedValue="scannedPassValue"
        @close-dialog="dialog.scanQRCode = false" />
        <v-divider class="my-3" />
        <v-row v-if="committedMembers.length > 0" no-gutters class="w-100 mt-5 ga-3">
            <template v-for="member, index in committedMembers" :key="member.nric">
                <CardMemberInfoSummary :member="membersDisplayed[index]" @remove="handleRemoveMember(index)" />
            </template>
        </v-row>
        <!-- <Snackbar v-model="messageSnackbar" :text="message" :color="messageColor" /> -->
    </v-row>
</template>

<script setup lang="ts">
import type { PropType } from 'vue'
import usePassKey from '../composables/usePassKey'
import useUtils from '../composables/useUtils'


const props = defineProps({
    type: {
        type: String,
        required: true
    },
    contractorType: {
        type: String,
        required: false
    },
    site: {
        type: String,
        required: true
    },
    selectedVisitorPass: {
        type: Array as PropType<TPassKeyPayload[]>,
        default: () => []
    }
})

const { requiredRule } = useUtils()
const { getPassKeysByPageSearch } = usePassKey()


const memberForm = reactive<TMemberInfo>({
    name: "",
    nric: "",
    visitorPass: [] as { keyId: string }[],
    contact: ""
})

const validForm = ref(false)
const formRef = ref<HTMLFormElement>()
const processing = ref(false);
const errorScanPassMessage = ref('')

const message = ref("");
const messageColor = ref("");
const messageSnackbar = ref(false);

function showMessage(msg: string, color: string) {
    message.value = msg;
    messageColor.value = color;
    messageSnackbar.value = true;
}

// pass
const passInput = ref('')
const passItems = ref<TPassKey[]>([])
const scannedPassValue = ref<string>("")

const dialog = reactive({
    scanQRCode: false,
})

const selectedPass = ref<string>('')

const members = defineModel<TMemberInfo[]>({ required: true, default: [] })
const committedMembers = ref<TMemberInfo[]>([])

// Always keep the model in sync: committed members + current form draft
watch(() => memberForm, (newForm) => {
    if (memberForm.name && memberForm.nric && memberForm.contact) {
        members.value = [...committedMembers.value, { ...newForm }]
    } else {
        members.value = [...committedMembers.value]
    }
}, { deep: true })


const passTypesComputed = computed(() => {
    if (props.type === 'contractor') {
        if (props.contractorType === 'property-agent') {
            return ["agent-pass"]
        } else {
            return ["contractor-pass"]
        }
    } else {
        return ["visitor-pass"]
    }
})

const { data: passesData, refresh: refreshPassesData, pending: fetchPassesPending } = await useLazyAsyncData('get-pass-keys', () => {
    return getPassKeysByPageSearch({
        search: passInput.value,
        page: 1,
        limit: 500,
        passTypes: passTypesComputed.value,
        sites: [props.site],
        statuses: ["Available"]
    })
})

watch(passesData, (data: any) => {
    passItems.value = Array.isArray(data?.items) ? data.items : []
})

const passItemsFilteredFinal = computed(() => {
    return passItems.value.filter((item: TPassKey) => {
        return !props.selectedVisitorPass.some((pass: TPassKeyPayload) => pass.keyId === item._id) && !committedMembers.value.some((member: TMemberInfo) => member.visitorPass?.some((pass) => pass.keyId === item._id))
    })
})

const membersDisplayed = computed(() => {
    return committedMembers.value.map((member: TMemberInfo) => {
        return {
            ...member,
            visitorPass: passItems.value.find((item: TPassKey) => item._id === member.visitorPass?.[0]?.keyId)?.prefixAndName || ""
        }
    })
})

function handleScanQRPass() {
    errorScanPassMessage.value = ""
    dialog.scanQRCode = true
}

watch(selectedPass, (newVal) => {
    memberForm.visitorPass = [{ keyId: newVal }]
})

watch(scannedPassValue, (newVal) => {
    if (!newVal) return

    const matchedPass = passItemsFilteredFinal.value.find((p) => p.prefixAndName === newVal)

    if (matchedPass) {
        selectedPass.value = matchedPass._id ?? ""
        return
    }

    errorScanPassMessage.value = "Scanned pass not available"
    showMessage("Scanned pass not available", "error")
})



function handleClearForm() {
    formRef.value?.reset()
}

async function handleAddMember() {
    committedMembers.value.push({ ...memberForm })
    handleClearForm()
}

function handleRemoveMember(index: number) {
    committedMembers.value = committedMembers.value.filter((_, i) => i !== index)
}



</script>

<style scoped></style>