<template>
    <div class="card p-3 parcel-card">
        <h2 class="h5 fw-semibold mb-3">📦 PostNL Parcels</h2>
        <!-- Parcel List -->
        <div v-if="parcels.length" class="mb-3">
            <div v-for="parcel in parcels" :key="parcel.tracking_code" class="border rounded p-2 mb-2">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <strong>{{ parcel.nickname }}</strong><br />
                        <small class="text-muted">{{ parcel.tracking_code }} • {{ parcel.postal_code }}</small>
                    </div>
                    <div class="d-flex justify-content-end align-items-center gap-2 mt-1">
                        <a :href="getPostNLUrl(parcel.tracking_code, parcel.postal_code)" class="btn btn-sm btn-outline-primary px-2 py-1" target="_blank" title="Track parcel">
                            🔍
                        </a>
                        <button @click="removeParcel(parcel.tracking_code)" class="btn btn-sm btn-outline-danger px-2 py-1" title="Remove parcel">
                            🗑
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <div v-else class="text-muted mb-3">No parcels tracked yet.</div>
        <!-- Sticky action bar -->
        <div class="sticky-bar">
            <button class="btn btn-primary w-100" @click="showAddModal = true">
                ➕ Add Parcel
            </button>
        </div>
        <!-- Add Parcel Modal -->
        <div class="modal fade" tabindex="-1" :class="{ show: showAddModal }" style="display: block;" v-if="showAddModal">
            <div class="modal-dialog">
                <div class="modal-content">
                    <form @submit.prevent="addParcel">
                        <div class="modal-header">
                            <h5 class="modal-title">Add New Parcel</h5>
                            <button type="button" class="btn-close" @click="showAddModal = false"></button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-2">
                                <input v-model="newNickname" type="text" placeholder="Parcel Nickname" class="form-control" required />
                            </div>
                            <div class="mb-2">
                                <input v-model="newTrackingCode" type="text" placeholder="Tracking Code" class="form-control" required />
                            </div>
                            <div class="mb-2">
                                <input v-model="newPostalCode" type="text" placeholder="Postal Code (e.g. 4133EX)" class="form-control" required />
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="submit" class="btn btn-primary">Add</button>
                            <button type="button" class="btn btn-secondary" @click="showAddModal = false">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    name: "ParcelTrackerCard",
    data() {
        return {
            parcels: [],
            newNickname: "",
            newTrackingCode: "",
            newPostalCode: "",
            showAddModal: false,
        };
    },
    async mounted() {
        await this.fetchParcels();
    },
    methods: {
        async fetchParcels() {
            try {
                const res = await fetch("https://192.168.70.11:8000/api/parcels");
                if (res.ok) {
                    const data = await res.json();
                    this.parcels = data.parcels;
                }
            } catch (error) {
                console.error("Error fetching parcels:", error);
            }
        },
        async addParcel() {
            if (!this.newNickname || !this.newTrackingCode || !this.newPostalCode) return;

            try {
                const res = await fetch("https://192.168.70.11:8000/api/parcels/add", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({
                        nickname: this.newNickname,
                        tracking_code: this.newTrackingCode,
                        postal_code: this.newPostalCode,
                    }),
                });
                if (res.ok) {
                    this.newNickname = "";
                    this.newTrackingCode = "";
                    this.newPostalCode = "";
                    this.showAddModal = false;
                    await this.fetchParcels();
                } else {
                    const errorData = await res.json();
                    alert("Failed to add parcel: " + (errorData.detail || "Unknown error"));
                }
            } catch (error) {
                alert("Error adding parcel: " + error.message);
            }
        },
        async removeParcel(trackingCode) {
            if (!confirm("Are you sure you want to remove this parcel?")) return;
            try {
                const res = await fetch(`https://192.168.70.11:8000/api/parcels/remove/${trackingCode}`, {
                    method: "DELETE",
                });
                if (res.ok) {
                    await this.fetchParcels();
                } else {
                    const err = await res.json();
                    alert("Failed to remove parcel: " + (err.detail || "Unknown error"));
                }
            } catch (error) {
                alert("Error removing parcel: " + error.message);
            }
        },
        getPostNLUrl(trackingCode, postalCode) {
            return `https://jouw.postnl.nl/track-and-trace/${trackingCode}-NL-${postalCode}`;
        },
    },
};
</script>
<style scoped>
.parcel-card {
    border-left: 5px solid #6b46c1;
    border-radius: 0.375rem;
    box-shadow: 0 4px 8px rgba(107, 70, 193, 0.15);
    background: white;
    padding-bottom: 4rem;
    /* give space for sticky bar */
}

/* Sticky bottom bar */
.sticky-bar {
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 0.75rem;
    background: white;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
    border-top: 1px solid #eee;
}

/* Bootstrap modal override for inline display */
.modal {
    background-color: rgba(0, 0, 0, 0.5);
}

.modal.show .modal-dialog {
    transform: translateY(0);
}
</style>