<template>
  <div>
    <PageHeader
      title="My Updates"
      subtitle="View and manage your updates"
      theme="stone"
      size="medium"
    />

    <section class="py-12 px-4">
      <UContainer class="px-4">
        <!-- Stats -->
        <div v-if="isAuthenticated && !pending" class="mb-8 flex items-center justify-between">
          <div class="text-ghost-300">
            <span class="text-2xl font-bold text-ghost-100">{{ total }}</span>
            {{ total === 1 ? "update" : "updates" }} posted
          </div>
          <UButton to="/updates/new" icon="i-lucide-plus"> New Update </UButton>
        </div>

        <!-- Loading State -->
        <div
          v-if="pending && !updates.length"
          class="flex justify-center items-center py-20"
        >
          <div class="text-center">
            <div
              class="w-8 h-8 border-4 border-ghost-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"
            ></div>
            <p class="text-ghost-400">Loading your updates...</p>
          </div>
        </div>

        <!-- Unauthenticated State -->
        <div
          v-else-if="!isAuthenticated"
          class="flex justify-center items-center py-20"
        >
          <div class="text-center max-w-md">
            <div class="w-16 h-16 bg-ghost-800 border border-ghost-600 rounded-full flex items-center justify-center mx-auto mb-4">
              <Icon name="heroicons:lock-closed" class="w-8 h-8 text-ghost-400" />
            </div>
            <h2 class="text-xl font-semibold text-ghost-100 mb-2">Sign in required</h2>
            <p class="text-ghost-400 mb-6">Please sign in to view your updates.</p>
            <UButton @click="openLoginModal({ title: 'Sign in to view your updates', description: 'Enter your email to access your updates' })">
              Sign In
            </UButton>
          </div>
        </div>

        <!-- Updates List -->
        <div v-else-if="updates.length" class="space-y-6">
          <UpdateCard
            v-for="update in updates"
            :key="update._id"
            :update="update"
            :show-preview="true"
            @edit="handleEdit"
            @delete="handleDelete"
          />

          <!-- Load More -->
          <div v-if="hasMore" class="flex justify-center pt-4">
            <UButton
              variant="outline"
              color="neutral"
              :loading="loadingMore"
              @click="loadMore"
            >
              Load More
            </UButton>
          </div>
        </div>

        <!-- Empty State -->
        <div v-else class="text-center py-20">
          <div class="w-16 h-16 mx-auto mb-4 opacity-50">
            <svg
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
              class="text-ghost-600"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"
              />
            </svg>
          </div>
          <h3 class="text-lg font-medium text-ghost-300 mb-2">
            No updates yet
          </h3>
          <p class="text-ghost-400 mb-6">
            Share your first update with the community
          </p>
          <UButton to="/updates/new" icon="i-lucide-plus">
            Post Your First Update
          </UButton>
        </div>
      </UContainer>
    </section>

    <!-- Delete Confirmation Modal -->
    <UModal
      v-model:open="showDeleteModal"
      title="Delete Update?"
      description="Are you sure you want to delete this update? This action cannot be undone."
    >
      <template #footer>
        <div class="flex justify-end gap-3">
          <UButton
            variant="ghost"
            color="neutral"
            @click="showDeleteModal = false"
          >
            Cancel
          </UButton>
          <UButton color="red" :loading="deleting" @click="confirmDelete">
            Delete
          </UButton>
        </div>
      </template>
    </UModal>
  </div>
</template>

<script setup>
const { isAuthenticated, checkMemberStatus } = useAuth();
const { openLoginModal } = useLoginModal();

const updates = ref([]);
const pending = ref(false);
const loadingMore = ref(false);
const hasMore = ref(false);
const total = ref(0);

const showDeleteModal = ref(false);
const updateToDelete = ref(null);
const deleting = ref(false);

// Check authentication
onMounted(async () => {
  if (!isAuthenticated.value) {
    const authenticated = await checkMemberStatus();
    if (!authenticated) {
      // Show login modal instead of redirecting
      openLoginModal({
        title: "Sign in to view your updates",
        description: "Enter your email to access your updates",
      });
      return;
    }
  }

  await loadUpdates();
});

// Load updates
const loadUpdates = async () => {
  pending.value = true;
  try {
    const response = await $fetch("/api/updates/my-updates", {
      params: { limit: 20, skip: 0 },
    });
    updates.value = response.updates;
    total.value = response.total;
    hasMore.value = response.hasMore;
  } catch (error) {
    console.error("Failed to load updates:", error);
  } finally {
    pending.value = false;
  }
};

// Load more updates
const loadMore = async () => {
  loadingMore.value = true;
  try {
    const response = await $fetch("/api/updates/my-updates", {
      params: { limit: 20, skip: updates.value.length },
    });
    updates.value.push(...response.updates);
    hasMore.value = response.hasMore;
  } catch (error) {
    console.error("Failed to load more updates:", error);
  } finally {
    loadingMore.value = false;
  }
};

// Handle edit
const handleEdit = (update) => {
  navigateTo(`/updates/${update._id}/edit`);
};

// Handle delete
const handleDelete = (update) => {
  updateToDelete.value = update;
  showDeleteModal.value = true;
};

// Confirm delete
const confirmDelete = async () => {
  if (!updateToDelete.value) return;

  deleting.value = true;
  try {
    await $fetch(`/api/updates/${updateToDelete.value._id}`, {
      method: "DELETE",
    });

    // Remove from list
    updates.value = updates.value.filter(
      (u) => u._id !== updateToDelete.value._id,
    );
    total.value--;

    showDeleteModal.value = false;
    updateToDelete.value = null;
  } catch (error) {
    console.error("Failed to delete update:", error);
    alert("Failed to delete update. Please try again.");
  } finally {
    deleting.value = false;
  }
};

useHead({
  title: "My Updates - Ghost Guild",
});
</script>
