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

const props = defineProps<{
  filename: string;
}>();

const schema = z.object({
  name: z
    .string({ error: "Required" })
    .min(1)
    .regex(/^[^/\\]+$/, "Invalid filename"),
});

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.filename,
});

const onSubmit = async (event: FormSubmitEvent<Schema>) => {
  submitting.value = true;
  try {
    await $fetch(`/api/files/${encodeURIComponent(props.filename)}`, {
      method: "PATCH",
      body: event.data,
    });
    toast.add({ title: "File renamed", color: "success" });
    emit("close", true);
  } catch (error) {
    toast.add({ title: getApiError(error), color: "error" });
  } finally {
    submitting.value = false;
  }
};
</script>

<template>
  <UModal title="Rename file">
    <template #body>
      <UForm :schema="schema" :state="state" class="space-y-4" @submit="onSubmit">
        <UFormField label="Name" name="name">
          <UInput v-model="state.name" class="w-full" />
        </UFormField>

        <div class="flex justify-end gap-2 pt-2">
          <UButton variant="ghost" @click="emit('close', false)">Cancel</UButton>
          <UButton type="submit" variant="subtle" :loading="submitting" icon="i-lucide-save">Save</UButton>
        </div>
      </UForm>
    </template>
  </UModal>
</template>
