<template>
  <div>
    <PageHeader
      title="Edit Update"
      subtitle="Make changes to your update"
      theme="stone"
      size="medium"
    />

    <section class="py-12 px-4">
      <UContainer class="px-4">
        <!-- Loading State -->
        <div
          v-if="loading"
          class="flex justify-center items-center py-20"
        >
          <div class="text-center">
            <div
              class="w-8 h-8 border-4 border-stone-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"
            ></div>
            <p class="text-stone-400">Loading update...</p>
          </div>
        </div>

        <!-- Edit Form -->
        <div v-else-if="update" class="max-w-3xl">
          <UpdateForm
            :initial-data="update"
            :submitting="submitting"
            :error="error"
            submit-label="Update"
            @submit="handleSubmit"
            @cancel="handleCancel"
          />

          <!-- Success Message -->
          <div
            v-if="success"
            class="mt-6 bg-green-500/10 border border-green-500/30 rounded-lg p-4"
          >
            <p class="text-green-300">✓ Update saved successfully!</p>
          </div>
        </div>

        <!-- Not Found -->
        <div v-else class="text-center py-20">
          <p class="text-stone-400 mb-4">Update not found</p>
          <UButton to="/updates" variant="outline" color="neutral">
            Back to Updates
          </UButton>
        </div>
      </UContainer>
    </section>
  </div>
</template>

<script setup>
const route = useRoute();
const { isAuthenticated, checkMemberStatus, memberData } = useAuth();

const update = ref(null);
const loading = ref(true);
const submitting = ref(false);
const error = ref(null);
const success = ref(false);

// Load update
const loadUpdate = async () => {
  loading.value = true;
  try {
    const data = await $fetch(`/api/updates/${route.params.id}`);

    // Check if user is the author
    if (memberData.value && data.author._id !== memberData.value.id) {
      error.value = "You can only edit your own updates";
      update.value = null;
      return;
    }

    update.value = data;
  } catch (err) {
    console.error("Failed to load update:", err);
    error.value = err.data?.statusMessage || "Failed to load update";
  } finally {
    loading.value = false;
  }
};

// Check authentication
onMounted(async () => {
  if (!isAuthenticated.value) {
    const authenticated = await checkMemberStatus();
    if (!authenticated) {
      await navigateTo("/login");
      return;
    }
  }

  await loadUpdate();
});

const handleSubmit = async (formData) => {
  submitting.value = true;
  error.value = null;
  success.value = false;

  try {
    await $fetch(`/api/updates/${route.params.id}`, {
      method: "PATCH",
      body: formData,
    });

    success.value = true;

    // Redirect to the update after a short delay
    setTimeout(() => {
      navigateTo(`/updates/${route.params.id}`);
    }, 1000);
  } catch (err) {
    console.error("Failed to update:", err);
    error.value =
      err.data?.statusMessage || "Failed to save update. Please try again.";
  } finally {
    submitting.value = false;
  }
};

const handleCancel = () => {
  navigateTo(`/updates/${route.params.id}`);
};

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