<template>
    <component :is="Default || 'div'">
    <div class="container mx-auto mt-20">
        <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-(--accent-blue-light) dark:text-(--accent-blue-dark) relative left-40" />
                </div>
                <UButton color="primary" @click="openCreateModal"
                    class="bg-(--accent-blue-light) dark:bg-(--accent-blue-dark) text-white hover:bg-(--accent-blue-dark) dark:hover:bg-(--accent-blue-light)">
                    <UIcon name="mdi:add-bold" />
                    {{ t('Add Address') }}
                </UButton>
            </div>
        </div>
        <div v-if="paginatedAddresses.length" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            <div v-for="address in 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-strat justify-end">
                    <p class="text-black dark:text-white">{{ address.street }}</p>
                    <p class="text-black dark:text-white">{{ address.zipCode }}, {{ address.city }}</p>
                    <p class="text-black dark:text-white">{{ address.country }}</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-(--accent-blue-light) dark:text-(--accent-blue-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.prevent="saveAddress" class="space-y-4" :validate="validate">
                        <div>
                            <label class="block text-sm font-medium text-black dark:text-white mb-1">Street *</label>
                            <UInput v-model="formData.street" placeholder="Enter street" name="street" class="w-full" />
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-black dark:text-white mb-1">Zip Code *</label>
                            <UInput v-model="formData.zipCode" placeholder="Enter zip code" name="zipCode"
                                class="w-full" />
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-black dark:text-white mb-1">City *</label>
                            <UInput v-model="formData.city" placeholder="Enter city" name="city" class="w-full" />
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-black dark:text-white mb-1">Country *</label>
                            <UInput v-model="formData.country" placeholder="Enter country" name="country"
                                class="w-full" />
                        </div>
                    </UForm>
                    <div class="flex justify-end gap-2">
                        <UButton variant="outline" color="neutral" @click="closeModal"
                            class="text-black dark:text-white">{{ t('Cancel') }}</UButton>
                        <UButton variant="outline" color="neutral" @click="saveAddress"
                            class="text-white bg-(--accent-blue-light) dark:bg-(--accent-blue-dark) hover:bg-(--accent-blue-dark) dark:hover:bg-(--accent-blue-light)">
                            {{ t('Save') }}</UButton>
                    </div>
                </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>
    </component>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useAddressStore } from '@/stores/address'
import { useI18n } from 'vue-i18n'
import Default from '@/layouts/default.vue'
const addressStore = useAddressStore()
const { t } = useI18n()
const searchQuery = ref('')
const showModal = ref(false)
const isEditing = ref(false)
const editingAddressId = ref<number | null>(null)
const formData = ref({ street: '', zipCode: '', city: '', country: '' })

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

const page = ref(addressStore.currentPage)
const paginatedAddresses = computed(() => addressStore.paginatedAddresses)
const totalItems = computed(() => addressStore.totalItems)
const pageSize = addressStore.pageSize

watch(page, (newPage) => addressStore.setPage(newPage))
watch(searchQuery, (val) => {
    addressStore.setSearchQuery(val)
})
function openCreateModal() {
    resetForm()
    isEditing.value = false
    showModal.value = true
}
function openEditModal(address: any) {
    formData.value = {
        street: address.street,
        zipCode: address.zipCode,
        city: address.city,
        country: address.country
    }
    isEditing.value = true
    editingAddressId.value = address.id
    showModal.value = true
}
function resetForm() {
    formData.value = { street: '', zipCode: '', city: '', country: '' }
    editingAddressId.value = null
}
function closeModal() {
    showModal.value = false
    resetForm()
}
function validate() {
    const errors = []
    if (!formData.value.street) errors.push({ name: 'street', message: 'Street required' })
    if (!formData.value.zipCode) errors.push({ name: 'zipCode', message: 'Zip Code required' })
    if (!formData.value.city) errors.push({ name: 'city', message: 'City required' })
    if (!formData.value.country) errors.push({ name: 'country', message: 'Country required' })
    return errors.length ? errors : null
}
function saveAddress() {
    if (validate()) return
    if (isEditing.value && editingAddressId.value) {
        addressStore.updateAddress(editingAddressId.value, formData.value)
    } else {
        addressStore.addAddress(formData.value)
    }
    closeModal()
}
function confirmDelete(id: number) {
    addressToDelete.value = id
    showDeleteConfirm.value = true
}
function deleteAddress() {
    if (addressToDelete.value) {
        addressStore.deleteAddress(addressToDelete.value)
    }
    showDeleteConfirm.value = false
    addressToDelete.value = null
}
</script>