<template>
    <v-card width="100%" :loading="processing">
        <v-toolbar>
            <v-row no-gutters class="fill-height px-6 d-flex justify-space-between align-center" align="center">
                <span class="font-weight-bold text-subtitle-1">{{ isEditMode ? 'Edit' : 'Assign' }} Pass &amp;
                    Keys</span>
                <ButtonClose @click="emit('close')" />
            </v-row>
        </v-toolbar>

        <v-card-text>
            <v-row no-gutters class="ga-1">
                <v-col cols="12">
                    <span class="text-subtitle-2 text-medium-emphasis">
                        Name: {{ prop.visitor.name }}
                    </span>
                </v-col>

                <!-- Pass section -->
                <v-col cols="12" class="mt-3">
                    <InputLabel title="Pass" />

                    <!-- Existing pass -->
                    <div v-if="existingPass" class="d-flex align-center ga-2 mb-2">
                        <v-chip prepend-icon="mdi-card-bulleted-outline" color="blue" variant="tonal" size="small"
                            closable @click:close="existingPass = null">
                            {{ existingPass.prefixAndName }}
                        </v-chip>
                        <span class="text-caption text-medium-emphasis">(current)</span>
                    </div>

                    <!-- New pass selector -->
                    <v-autocomplete v-if="!existingPass" v-model="selectedPass" v-model:search="passInput"
                        :hide-no-data="false" :items="passItems" item-title="prefixAndName" item-value="_id"
                        variant="outlined" hide-details density="compact" small-chips :loading="fetchPassesPending"
                        clearable>
                        <template v-slot:chip="{ props: chipProps, item }">
                            <v-chip v-if="selectedPass" v-bind="chipProps" prepend-icon="mdi-card-bulleted-outline"
                                :text="item.raw?.prefixAndName" />
                        </template>
                        <template v-slot:no-data>
                            <v-list-item density="compact">
                                <v-list-item-title>No available passes</v-list-item-title>
                            </v-list-item>
                        </template>
                    </v-autocomplete>
                </v-col>

                <!-- Keys section -->
                <v-col v-if="showKeys" cols="12" class="mt-3">
                    <InputLabel title="Keys" />

                    <!-- Existing keys -->
                    <div v-if="existingKeys.length > 0" class="d-flex flex-wrap ga-1 mb-2">
                        <v-chip v-for="key in existingKeys" :key="key.keyId" prepend-icon="mdi-key" color="orange"
                            variant="tonal" size="small" closable @click:close="removeExistingKey(key.keyId)">
                            {{ key.prefixAndName }}
                        </v-chip>
                        <span class="text-caption text-medium-emphasis align-self-center">(current)</span>
                    </div>

                    <!-- New keys selector -->
                    <v-autocomplete v-model="selectedKeys" v-model:search="keyInput" :hide-no-data="false"
                        :items="keyItems" item-title="prefixAndName" item-value="_id"
                        :label="existingKeys.length > 0 ? 'Add more keys' : undefined" multiple variant="outlined"
                        hide-details density="compact" small-chips :loading="fetchKeysPending">
                        <template v-slot:chip="{ props: chipProps, item }">
                            <v-chip v-if="selectedKeys.length > 0" v-bind="chipProps" prepend-icon="mdi-key"
                                :text="item.raw?.prefixAndName" />
                        </template>
                        <template v-slot:no-data>
                            <v-list-item density="compact">
                                <v-list-item-title>No available keys</v-list-item-title>
                            </v-list-item>
                        </template>
                    </v-autocomplete>
                </v-col>
            </v-row>

            <v-row v-if="errorMessage" no-gutters class="mt-2">
                <p class="text-error text-subtitle-2 w-100 text-center">{{ errorMessage }}</p>
            </v-row>
        </v-card-text>

        <v-toolbar density="compact">
            <v-row no-gutters>
                <v-col cols="6">
                    <v-btn tile block variant="text" class="text-none" size="48" text="Cancel" @click="emit('close')" />
                </v-col>
                <v-col cols="6">
                    <v-btn tile block variant="flat" color="black" class="text-none" size="48"
                        :text="isEditMode ? 'Save' : 'Assign'" :disabled="!canSubmit" :loading="processing"
                        @click="handleSubmit" />
                </v-col>
            </v-row>
        </v-toolbar>
    </v-card>
</template>

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

const prop = defineProps({
    visitor: {
        type: Object as PropType<TVisitor>,
        required: true,
    },
    site: {
        type: String,
        required: true,
    },
    mode: {
        type: String as PropType<'add' | 'edit'>,
        default: 'add',
    },
})

const emit = defineEmits<{
    (e: 'done'): void
    (e: 'close'): void
}>()

const { getPassKeysByPageSearch } = usePassKey()
const { updateVisitorPassKey } = useVisitor()

const processing = ref(false)
const errorMessage = ref('')

// New selections
const selectedPass = ref<string>('')
const selectedKeys = ref<string[]>([])
const passInput = ref('')
const keyInput = ref('')
const passItems = ref<TPassKey[]>([])
const keyItems = ref<TPassKey[]>([])

// Existing pass/keys (editable)
const existingPass = ref<{ keyId: string; prefixAndName: string } | null>(null)
const existingKeys = ref<{ keyId: string; prefixAndName: string }[]>([])

const isEditMode = computed(() => prop.mode === 'edit')
const showKeys = computed(() => prop.visitor.type === 'contractor')

const passTypesComputed = computed(() => {
    const type = prop.visitor.type
    const contractorType = (prop.visitor as any).contractorType
    if (type === 'contractor') {
        return contractorType === 'property-agent' ? ['agent-pass'] : ['contractor-pass']
    }
    return ['visitor-pass']
})

// Initialise existing values in edit mode
onMounted(() => {
    if (isEditMode.value) {
        const vPass = prop.visitor.visitorPass
        if (Array.isArray(vPass) && vPass.length > 0) {
            const p = vPass[0] as any
            existingPass.value = { keyId: p.keyId, prefixAndName: p.prefixAndName }
        }
        const vKeys = prop.visitor.passKeys
        if (Array.isArray(vKeys) && vKeys.length > 0) {
            existingKeys.value = (vKeys as any[]).map(k => ({ keyId: k.keyId, prefixAndName: k.prefixAndName }))
        }
    }
})

function removeExistingKey(keyId: string) {
    existingKeys.value = existingKeys.value.filter(k => k.keyId !== keyId)
}

// Exclude already-held pass/keys from selectable lists
const existingPassId = computed(() => existingPass.value?.keyId)
const existingKeyIds = computed(() => existingKeys.value.map(k => k.keyId))

const { data: passesData, refresh: refreshPasses, pending: fetchPassesPending } = await useLazyAsyncData(
    `add-pass-key-visitor-passes-${prop.visitor._id}`,
    () => getPassKeysByPageSearch({
        search: passInput.value,
        page: 1,
        limit: 500,
        passTypes: passTypesComputed.value,
        sites: [prop.site],
        statuses: ['Available'],
    })
)

const { data: keysData, refresh: refreshKeys, pending: fetchKeysPending } = await useLazyAsyncData(
    `add-pass-key-visitor-keys-${prop.visitor._id}`,
    () => getPassKeysByPageSearch({
        search: keyInput.value,
        page: 1,
        limit: 500,
        passTypes: ['pass-key'],
        sites: [prop.site],
        statuses: ['Available'],
    })
)

watch(passesData, (data: any) => {
    const all: TPassKey[] = Array.isArray(data?.items) ? data.items : []
    passItems.value = all.filter(p => p._id !== existingPassId.value)
})

watch(keysData, (data: any) => {
    const all: TPassKey[] = Array.isArray(data?.items) ? data.items : []
    keyItems.value = all.filter(k => !existingKeyIds.value.includes(k._id!))
})

// Re-filter when existing items change
watch([existingPassId, existingKeyIds], () => {
    const rawPasses = (passesData.value as any)?.items ?? []
    passItems.value = rawPasses.filter((p: TPassKey) => p._id !== existingPassId.value)
    const rawKeys = (keysData.value as any)?.items ?? []
    keyItems.value = rawKeys.filter((k: TPassKey) => !existingKeyIds.value.includes(k._id!))
}, { deep: true })

const canSubmit = computed(() => {
    if (isEditMode.value) {
        // allow save if anything changed: existing items modified OR new items selected
        return existingPass.value !== null || selectedPass.value ||
            existingKeys.value.length > 0 || selectedKeys.value.length > 0
    }
    return !!selectedPass.value || selectedKeys.value.length > 0
})

async function handleSubmit() {
    if (!prop.visitor._id) return
    errorMessage.value = ''
    processing.value = true

    try {
        const payload: any = {}

        // Build final pass list: kept existing + newly selected
        const finalPasses: { keyId: string }[] = []
        if (existingPass.value) {
            finalPasses.push({ keyId: existingPass.value.keyId })
        }
        if (selectedPass.value) {
            finalPasses.push({ keyId: selectedPass.value})
        }
        payload.visitorPass = finalPasses

        // Build final keys list: kept existing + newly selected
        if (showKeys.value) {
            const finalKeys: { keyId: string}[] = [
                ...existingKeys.value.map(k => ({ keyId: k.keyId })),
                ...selectedKeys.value.map(keyId => ({ keyId })),
            ]
            payload.passKeys = finalKeys
        }

        await updateVisitorPassKey(prop.visitor._id, payload)
        emit('done')
        emit('close')
    } catch (error: any) {
        errorMessage.value = error?.data?.message || 'Failed to save pass & keys. Please try again.'
    } finally {
        processing.value = false
    }
}
</script>

<style scoped></style>

