<script setup lang="ts">
import { z } from "zod";
import type { FormSubmitEvent } from "@nuxt/ui";

const props = defineProps<{
  link: Link | null;
}>();

const schema = z.object({
  name: z.string({ error: "Required" }),
  path: z.string({ error: "Required" }),
  url: z.url({ error: (err) => err.code === "invalid_type" ? "Required" : "Invalid format", }),
  disabled: z.boolean().optional(),
});

type Schema = z.output<typeof schema>;

const emit = defineEmits<{ close: [value: boolean] }>();

const toast = useToast();
const submitting = ref(false);

const state = reactive<Partial<Schema>>({
  name: props.link?.name,
  path: props.link?.path,
  url: props.link?.url,
  disabled: props.link?.disabled ?? false,
});

const onSubmit = async (event: FormSubmitEvent<Schema>) => {
  submitting.value = true;
  try {
    if (props.link) {
      await $fetch(`/api/links/${props.link.id}`, { method: "PATCH", body: event.data, });
      toast.add({ title: "Link updated", color: "success" });
    } else {
      await $fetch("/api/links", { method: "POST", body: event.data });
      toast.add({ title: "Link created", color: "success" });
    }
    emit("close", true);
  } catch (error) {
    toast.add({ title: getApiError(error), color: "error" });
  } finally {
    submitting.value = false;
  }
}
</script>

<template>
  <UModal :title="link ? 'Edit link' : 'New link'">
    <template #body>
      <UForm
        :schema="schema"
        :state="state"
        class="space-y-4"
        @submit="onSubmit"
      >
        <UFormField label="Name" name="name">
          <UInput v-model="state.name" placeholder="my-link" class="w-full" />
        </UFormField>

        <UFormField label="Path" name="path">
          <UInput v-model="state.path" placeholder="/go/somewhere" class="w-full" />
        </UFormField>

        <UFormField label="URL" name="url">
          <UInput v-model="state.url" placeholder="https://example.com" class="w-full" />
        </UFormField>

        <UFormField name="disabled">
          <UCheckbox v-model="state.disabled" label="Disabled" />
        </UFormField>

        <div class="flex justify-end gap-2 pt-2">
          <UButton variant="ghost" @click="emit('close', false)">Cancel</UButton>
          <UButton type="submit" :loading="submitting">{{ link ? "Save" : "Create" }}</UButton>
        </div>
      </UForm>
    </template>
  </UModal>
</template>
