<template>
            <div class="">
            <div class="flex flex-col gap-5 mb-6">
                <h1 class="text-2xl font-bold text-black dark:text-white">{{ t('Addresses') }}</h1>
                <div class="flex md:flex-row flex-col justify-between items-start md:items-center gap-5 md:gap-0">
                    <div class="flex gap-2 items-center">
                        <UInput v-model="searchQuery" type="text" :placeholder="t('Search address')"
                            class="bg-white dark:bg-gray-800 text-black dark:text-white absolute" />
                        <UIcon name="ic:baseline-search"
                            class="text-[20px] text-(--text-sky-light) dark:text-(--text-sky-dark) relative left-40" />
                    </div>
                    <UButton color="info" @click="openCreateModal">
                        <UIcon name="mdi:add-bold" />
                        {{ t('Add Address') }}
                    </UButton>
                </div>
            </div>
            <div v-if="cartStore.addressLoading" class="text-center py-8 text-gray-500 dark:text-gray-400">
                {{ t('Loading addresses...') }}
            </div>
            <div v-else-if="cartStore.addressError" class="text-center py-8 text-red-500 dark:text-red-400">
                {{ cartStore.addressError }}
            </div>
            <div v-else-if="cartStore.paginatedAddresses.length"
                class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                <div v-for="address in cartStore.paginatedAddresses" :key="address.id"
                    class="border border-(--border-light) dark:border-(--border-dark) rounded-md p-4 bg-(--second-light) dark:bg-(--main-dark) hover:shadow-md transition-shadow flex justify-between">
                    <div class="flex flex-col gap-2 items-start justify-end">
                        <p class="text-black dark:text-white font-semibold">{{ address.address_info.recipient }}</p>
                        <p class="text-black dark:text-white">{{ address.address_info.street }} {{
                            address.address_info.building_no }}{{ address.address_info.apartment_no ? '/' +
                                address.address_info.apartment_no : '' }}</p>
                        <p class="text-black dark:text-white">{{ address.address_info.postal_code }}, {{
                            address.address_info.city }}</p>
                        <p class="text-black dark:text-white">{{ address.address_info.voivodeship }}</p>
                        <p v-if="address.address_info.address_line2" class="text-black dark:text-white">{{
                            address.address_info.address_line2 }}</p>
                    </div>
                    <div class="flex flex-col items-end justify-between gap-2">
                        <button @click="confirmDelete(address.id)"
                            class="p-2 text-red-500 bg-red-100 dark:bg-(--main-dark)  rounded transition-colors"
                            :title="t('Remove')">
                            <UIcon name="material-symbols:delete" class="text-[18px]" />
                        </button>
                        <UButton size="sm" color="neutral" variant="outline" @click="openEditModal(address)"
                            class="text-(--text-sky-light) dark:text-(--text-sky-dark) text-[13px]">
                            {{ t('edit') }}
                            <UIcon name="ic:sharp-edit" class="text-[15px]" />
                        </UButton>
                    </div>
                </div>
            </div>
            <div v-else class="text-center py-8 text-gray-500 dark:text-gray-400">{{ t('No addresses found') }}</div>
            <div class="mt-6 flex justify-center">
                <UPagination v-model:page="page" :total="totalItems" :page-size="pageSize" />
            </div>
            <UModal v-model:open="showModal" :overlay="true" class="max-w-md mx-auto">
                <template #content>
                    <div class="p-6 flex flex-col gap-6">
                        <p class="text-[20px] text-black dark:text-white ">Address</p>
                        <UForm @submit="saveAddress" class="space-y-4" :validate="validate" :state="formData">
                            <template v-for="field in formFieldKeys" :key="field">
                                <UFormField :label="fieldLabel(field)" :name="field"
                                    :required="field !== 'address_line2'">
                                    <UInput v-model="formData[field]" :placeholder="fieldLabel(field)" class="w-full" />
                                </UFormField>
                            </template>

                            <div class="flex justify-end gap-2">
                                <UButton variant="outline" color="neutral" @click="closeModal">
                                    {{ t('Cancel') }}
                                </UButton>

                                <UButton type="submit" color="info" class="cursor-pointer">
                                    {{ t('Save') }}
                                </UButton>
                            </div>
                        </UForm>
                    </div>
                </template>
            </UModal>
            <UModal v-model:open="showDeleteConfirm" :overlay="true" class="max-w-md mx-auto">
                <template #content>
                    <div class="p-6 flex flex-col gap-3">
                        <div class="flex flex-col gap-2 justify-center items-center">
                            <p class="flex items-end gap-2 dark:text-white text-black">
                                <UIcon name='f7:exclamationmark-triangle' class="text-[35px] text-red-700" />
                                Confirm Delete
                            </p>
                            <p class="text-gray-700 dark:text-gray-300">
                                {{ t('Are you sure you want to delete this address?') }}</p>
                        </div>
                        <div class="flex justify-center gap-5">
                            <UButton variant="outline" color="neutral" @click="showDeleteConfirm = false"
                                class="dark:text-white text-black">{{ t('Cancel') }}
                            </UButton>
                            <UButton variant="outline" color="neutral" @click="deleteAddress" class="text-red-700">
                                {{ t('Delete') }}</UButton>
                        </div>
                    </div>
                </template>
            </UModal>
        </div>
    </template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useCartStore } from '@/stores/customer/cart'
import { useI18n } from 'vue-i18n'
import { currentCountry } from '@/router/langs'

type AddressFormState = Record<string, string>

const cartStore = useCartStore()
const { t } = useI18n()
const searchQuery = ref(cartStore.addressSearchQuery)
const showModal = ref(false)
const isEditing = ref(false)
const editingAddressId = ref<number | null>(null)
const addressTemplate = ref<AddressFormState | null>(null)
const formData = reactive<AddressFormState>({})

const showDeleteConfirm = ref(false)
const addressToDelete = ref<number | null>(null)

const page = computed<number>({
    get: () => cartStore.addressCurrentPage,
    set: (value: number) => cartStore.setAddressPage(value)
})
const totalItems = computed(() => cartStore.totalAddressItems)
const pageSize = cartStore.addressPageSize
const formFieldKeys = computed(() => (addressTemplate.value ? Object.keys(addressTemplate.value) : []))

watch(searchQuery, (val) => {
    cartStore.setAddressSearchQuery(val)
})

onMounted(() => {
    cartStore.fetchAddresses()
})

function clearFormData() {
    Object.keys(formData).forEach((key) => delete formData[key])
}

function fieldLabel(key: string) {
    const labels: Record<string, string> = {
        postal_code: 'Zip Code',
        post_town: 'City',
        city: 'City',
        county: 'County',
        region: 'Region',
        voivodeship: 'Region / Voivodeship',
        street: 'Street',
        thoroughfare: 'Street',
        building_no: 'Building No',
        building_name: 'Building Name',
        house_number: 'House Number',
        orientation_number: 'Orientation Number',
        apartment_no: 'Apartment No',
        sub_building: 'Sub Building',
        address_line2: 'Address Line 2',
        recipient: 'Recipient'
    }

    return t(labels[key] ?? key.replace(/_/g, ' ').replace(/\b\w/g, (chr) => chr.toUpperCase()))
}

async function openCreateModal() {
    resetForm()
    isEditing.value = false

    const template = await cartStore.getAddressTemplate(Number(currentCountry.value?.id) | 2).catch(() => null)
    if (template) {
        addressTemplate.value = template
        clearFormData()
        Object.assign(formData, template)
    }

    showModal.value = true
}

async function openEditModal(address: any) {
    currentCountry.value = address.country_id || 1
    const template = await cartStore.getAddressTemplate(address.country_id | 2).catch(() => null)

    if (template) {
        addressTemplate.value = template
        clearFormData()
        Object.assign(formData, template)
    }

    if (address.address_info) {
        formFieldKeys.value.forEach((key) => {
            formData[key] = address.address_info[key] ?? ''
        })
    }

    isEditing.value = true
    editingAddressId.value = address.id
    showModal.value = true
}

function resetForm() {
    clearFormData()
    editingAddressId.value = null
}

function closeModal() {
    showModal.value = false
    resetForm()
}

function validate() {
    const errors: Array<{ name: string; message: string }> = []
    const optionalFields = new Set(['address_line2'])

    formFieldKeys.value.forEach((key) => {
        if (!optionalFields.has(key) && !formData[key]?.trim()) {
            errors.push({ name: key, message: `${fieldLabel(key)} required` })
        }
    })

    return errors
}

async function saveAddress() {
    if (isEditing.value && editingAddressId.value) {
        await cartStore.updateAddress(editingAddressId.value, currentCountry.value?.id || 2, formData)
    } else {
        await cartStore.addAddress(currentCountry.value?.id || 2, formData)
    }
    closeModal()
}

function confirmDelete(id: number) {
    addressToDelete.value = id
    showDeleteConfirm.value = true
}

async function deleteAddress() {
    if (addressToDelete.value) {
        await cartStore.deleteAddress(addressToDelete.value)
    }
    showDeleteConfirm.value = false
    addressToDelete.value = null
}
</script>