<template>
    <div class="address-selector">
        <!-- Address Display -->
        <div v-if="selectedAddress" class="selected-address">
            <div class="address-card">
                <div class="address-header">
                    <h6 class="address-name">
                        <i class="fas fa-user me-2"></i>
                        {{ selectedAddress.Name }}
                    </h6>
                    <div class="address-phone">
                        <i class="fas fa-phone me-1"></i>
                        {{ selectedAddress.PhoneNumber1 }}
                    </div>
                </div>
                <div class="address-body">
                    <div class="address-location">
                        <i class="fas fa-map-marker-alt me-2 text-danger"></i>
                        {{ selectedAddress.FullAddress || formatAddress(selectedAddress) }}
                    </div>
                    <div v-if="selectedAddress.Note" class="address-note">
                        <i class="fas fa-sticky-note me-2 text-warning"></i>
                        {{ selectedAddress.Note }}
                    </div>
                </div>
                <div class="address-actions">
                    <button class="btn btn-sm btn-outline-primary" @click="changeAddress">
                        <i class="fas fa-edit me-1"></i>Thay đổi
                    </button>
                </div>
            </div>
        </div>

        <!-- Address Selection -->
        <div v-else class="address-selection">
            <div class="text-center py-4">
                <div class="address-placeholder mb-3">
                    <i class="fas fa-map-marker-alt text-muted" style="font-size: 3rem;"></i>
                </div>
                <p class="text-muted mb-3">Chưa chọn địa chỉ</p>
                <div class="btn-group">
                    <button class="btn btn-outline-primary" @click="showAddressList = true">
                        <i class="fas fa-list me-2"></i>Chọn địa chỉ có sẵn
                    </button>
                    <button class="btn btn-primary" @click="showAddressForm = true">
                        <i class="fas fa-plus me-2"></i>Tạo địa chỉ mới
                    </button>
                </div>
            </div>
        </div>

        <!-- Address List Modal -->
        <LadaDialog :visible="showAddressList">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Chọn địa chỉ {{ addressTypeText }}</h5>
                    <button @click="showAddressList = false" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <div class="address-list-modal">
                    <div v-if="addresses.length > 0" class="address-list">
                        <div v-for="address in addresses" :key="address.Id" class="address-item"
                            @click="selectAddress(address)">
                            <div class="address-item-info">
                                <h6 class="address-item-name">{{ address.ContactName }}</h6>
                                <p class="address-item-phone">{{ address.ContactPhoneNumber }}</p>
                                <p class="address-item-address">{{ address.FullAddress || formatAddress(address) }}</p>
                            </div>
                            <div class="address-item-action">
                                <i class="fas fa-chevron-right text-muted"></i>
                            </div>
                        </div>
                    </div>
                    <div v-else class="no-addresses">
                        <div class="text-center py-4">
                            <i class="fas fa-map-marker-alt text-muted mb-3" style="font-size: 3rem;"></i>
                            <p class="text-muted">Không có địa chỉ nào</p>
                            <button class="btn btn-primary" @click="showAddressForm = true">
                                <i class="fas fa-plus me-2"></i>Tạo địa chỉ mới
                            </button>
                        </div>
                    </div>
                </div>
            </template>
        </LadaDialog>

        <!-- Address Form Modal -->
        <LadaDialog :visible="showAddressForm">
            <template #header>
                <div class="modal-header">
                    <h5 class="modal-title">Tạo địa chỉ mới</h5>
                    <button @click="showAddressForm = false" type="button" class="close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </template>
            <template #body>
                <AddressAdd @submit="onAddressCreated" @cancel="showAddressForm = false" :add-type="addressType"
                    :customer-id="customerId" />
            </template>
        </LadaDialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { useToast } from "vue-toastification";

// Services
import customerAddressService from "@/services/customerAddressService";

// Components
import LadaDialog from '@/components/dialogs/ladaDialog.vue';
import AddressAdd from './address-add.vue';

const toast = useToast();

// Props
const props = defineProps({
    customerId: Number,
    addressType: Number
});

// Emits
const emit = defineEmits(['address-selected']);

// Reactive data
const selectedAddress = ref(null);
const addresses = ref([]);
const showAddressList = ref(false);
const showAddressForm = ref(false);

// Computed
const addressTypeText = computed(() => {
    return props.addressType === 1 ? 'gửi hàng' : 'nhận hàng';
});

// Methods
const loadAddresses = async () => {
    if (!props.customerId) {
        addresses.value = [];
        return;
    }
    try {
        const searchModel = {
            Pagination: {
                Total: 0,
                PageIndex: 1,
                PageSize: 50
            },
            Sort: {
                Predicate: '',
                Reverse: true
            },
            Search: {
                PredicateObject: {
                    Keyword: '',
                    AddressType: props.addressType,
                    CustomerId: props.customerId
                }
            }
        };
        const result = await customerAddressService.search(searchModel);
        addresses.value = (result && result.Items) ? result.Items : [];
    } catch (error) {
        toast.error('Lỗi khi tải danh sách địa chỉ');
        addresses.value = [];
    }
};

const selectAddress = (address) => {
    selectedAddress.value = {
        Id: address.Id,
        Name: address.ContactName,
        PhoneNumber1: address.ContactPhoneNumber,
        FullAddress: address.FullAddress,
        Address1: address.Address,
        CityId: address.CityId,
        DistrictId: address.DistrictId,
        WardId: address.WardId,
        Note: address.Note
    };

    emit('address-selected', selectedAddress.value);
    showAddressList.value = false;
};

const changeAddress = () => {
    selectedAddress.value = null;
    emit('address-selected', null);
};

const onAddressCreated = async (address) => {
    showAddressForm.value = false;

    // Reload addresses
    await loadAddresses();

    // Auto-select the new address
    const newAddress = addresses.value.find(addr => addr.Id === address.Id);
    if (newAddress) {
        selectAddress(newAddress);
    }
};

// Lifecycle
onMounted(() => {
    loadAddresses();
});

// Watch customerId để load lại địa chỉ khi thay đổi khách hàng
watch(
    () => props.customerId,
    (newVal, oldVal) => {
        if (newVal && newVal !== oldVal) {
            loadAddresses();
            selectedAddress.value = null;
        }
    }
);

function formatAddress(addr) {
    let parts = [];
    if (addr.Address) parts.push(addr.Address);
    if (addr.WardId) parts.push('Phường/Xã: ' + addr.WardId);
    if (addr.DistrictId) parts.push('Quận/Huyện: ' + addr.DistrictId);
    if (addr.CityId) parts.push('Tỉnh/TP: ' + addr.CityId);
    return parts.join(', ');
}
</script>

<style scoped>
.address-selector {
    min-height: 200px;
}

.selected-address {
    height: 100%;
}

.address-card {
    border: 2px solid #e9ecef;
    border-radius: 10px;
    padding: 20px;
    background-color: #f8f9fa;
    transition: all 0.3s ease;
}

.address-card:hover {
    border-color: #007bff;
    box-shadow: 0 0 10px rgba(0, 123, 255, 0.1);
}

.address-header {
    margin-bottom: 15px;
}

.address-name {
    margin: 0;
    color: #333;
    font-weight: 600;
}

.address-phone {
    color: #6c757d;
    font-size: 14px;
    margin-top: 5px;
}

.address-body {
    margin-bottom: 15px;
}

.address-location {
    color: #555;
    margin-bottom: 10px;
    line-height: 1.4;
}

.address-note {
    color: #6c757d;
    font-size: 14px;
    font-style: italic;
}

.address-actions {
    text-align: right;
}

.address-selection {
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.address-placeholder {
    opacity: 0.5;
}

.btn-group {
    gap: 10px;
}

/* Address List Modal */
.address-list-modal {
    max-height: 400px;
    overflow-y: auto;
}

.address-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.address-item {
    display: flex;
    align-items: center;
    padding: 15px;
    border: 2px solid #e9ecef;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.address-item:hover {
    border-color: #007bff;
    background-color: #f8f9fa;
}

.address-item-info {
    flex: 1;
}

.address-item-name {
    margin: 0;
    font-weight: 600;
    color: #333;
}

.address-item-phone {
    margin: 5px 0;
    color: #6c757d;
    font-size: 14px;
}

.address-item-address {
    margin: 0;
    color: #555;
    font-size: 14px;
    line-height: 1.3;
}

.address-item-action {
    color: #6c757d;
    font-size: 18px;
}

.no-addresses {
    padding: 20px;
}

/* Responsive */
@media (max-width: 768px) {
    .btn-group {
        flex-direction: column;
    }

    .address-card {
        padding: 15px;
    }

    .address-item {
        flex-direction: column;
        align-items: flex-start;
    }

    .address-item-action {
        align-self: flex-end;
        margin-top: 10px;
    }
}
</style>