<script setup lang="ts">
import type { Project } from "@workspace/schema";

definePageMeta({
  title: "Edit Project",
});

const route = useRoute();
const router = useRouter();
const { updateProject } = useProjectApi();

const saving = ref(false);
const project = ref<Project | null>(null);
const loading = ref(true);
const notFound = ref(false);

const config = useRuntimeConfig();
const apiBase = config.public.apiBaseUrl as string;

onMounted(async () => {
  const res = await fetch(`${apiBase}/projects/${route.params.id}`);
  if (!res.ok) {
    notFound.value = true;
  } else {
    project.value = await res.json();
  }
  loading.value = false;
});

async function handleSubmit(body: { name: string; description?: string; status: string }) {
  saving.value = true;
  const updated = await updateProject(route.params.id as string, body);
  saving.value = false;
  if (updated) router.push("/projects");
}
</script>

<template>
  <UPage>
    <UPageHeader title="Edit Project" description="Update project details">
      <template #right>
        <UButton label="Back" icon="i-lucide-chevron-left" color="neutral" variant="outline" to="/projects" />
      </template>
    </UPageHeader>

    <UPageBody>
      <UAlert v-if="notFound" color="warning" variant="soft" icon="i-lucide-alert-triangle" title="Project not found" />

      <UProgress v-else-if="loading" />

      <UCard v-else-if="project">
        <ProjectForm
          :name="project.name"
          :description="project.description ?? undefined"
          :status="project.status"
          :saving
          @submit="handleSubmit"
        />
      </UCard>
    </UPageBody>
  </UPage>
</template>
