<script setup lang="ts">
import { ref } from 'vue';

const props = defineProps<{
  open: boolean;
  folderId?: string | null;
}>();

const emit = defineEmits(['update:open', 'created']);

const form = ref({
  title: '',
  url: '',
  description: '',
  icon: 'i-lucide-globe',
  color: '#ffffff'
});
const loading = ref(false);

const close = () => {
  emit('update:open', false);
  form.value = { title: '', url: '', description: '', icon: 'i-lucide-globe', color: '#ffffff' };
};

const create = async () => {
  if (!form.value.title || !form.value.url) return;
  loading.value = true;
  try {
    await $fetch('/api/links', {
      method: 'POST',
      body: { ...form.value, folderId: props.folderId }
    });
    emit('created');
    close();
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <UModal :open="open" @update:open="$emit('update:open', $event)">
    <template #content>
      <UCard>
        <template #header>
          <h3 class="text-xl font-semibold">New Link</h3>
        </template>

        <form @submit.prevent="create" class="space-y-4">
          <UFormGroup label="Title">
            <UInput v-model="form.title" placeholder="E.g., Google" required />
          </UFormGroup>

          <UFormGroup label="URL">
            <UInput v-model="form.url" placeholder="https://google.com" type="url" required />
          </UFormGroup>

          <UFormGroup label="Description (Optional)">
            <UTextarea v-model="form.description" placeholder="A brief description..." />
          </UFormGroup>

          <div class="grid grid-cols-2 gap-4">
            <UFormGroup label="Icon (Iconify Name)">
              <UInput v-model="form.icon" placeholder="i-lucide-link" />
            </UFormGroup>

            <UFormGroup label="Color">
              <UInput v-model="form.color" type="color" class="h-8" />
            </UFormGroup>
          </div>
          
          <div class="flex justify-end gap-3 mt-6">
            <UButton color="neutral" variant="ghost" @click="close">Cancel</UButton>
            <UButton type="submit" :loading="loading">Create</UButton>
          </div>
        </form>
      </UCard>
    </template>
  </UModal>
</template>
