<template>
  <div class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md mx-4">
      <!-- Header -->
      <div class="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
        <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Save Request</h3>
        <rs-button
          variant="text"
          size="sm"
          @click="$emit('close')"
          class="p-2"
        >
          <Icon name="ic:outline-close" size="16" />
        </rs-button>
      </div>

      <!-- Content -->
      <div class="p-6">
        <FormKit
          type="text"
          v-model="requestName"
          label="Request Name"
          placeholder="Enter request name"
          validation="required"
          outer-class="mb-4"
        />
        
        <FormKit
          type="select"
          v-model="selectedCollectionId"
          label="Collection"
          :options="collectionOptions"
          validation="required"
          outer-class="mb-4"
        />

        <div v-if="!selectedCollectionId" class="text-center py-4">
          <p class="text-sm text-gray-500 dark:text-gray-400 mb-3">No collections available</p>
          <rs-button
            variant="primary"
            size="sm"
            @click="createNewCollection"
          >
            Create New Collection
          </rs-button>
        </div>
      </div>

      <!-- Footer -->
      <div class="flex items-center justify-end gap-3 p-6 border-t border-gray-200 dark:border-gray-700">
        <rs-button
          variant="secondary"
          @click="$emit('close')"
        >
          Cancel
        </rs-button>
        <rs-button
          variant="primary"
          @click="saveRequest"
          :disabled="!requestName.trim() || !selectedCollectionId"
        >
          Save Request
        </rs-button>
      </div>
    </div>
  </div>
</template>

<script setup>
const emit = defineEmits(['close'])

const {
  collections,
  httpMethod,
  requestUrl,
  requestParams,
  requestHeaders,
  requestAuth,
  requestBody,
  requestName: globalRequestName,
  showNotification
} = useApiPlatform()

const requestName = ref(globalRequestName.value || 'Untitled Request')
const selectedCollectionId = ref('')

// Compute collection options for the dropdown
const collectionOptions = computed(() => {
  return collections.value.map(collection => ({
    label: collection.name,
    value: collection.id
  }))
})

const saveRequest = () => {
  if (!requestName.value.trim() || !selectedCollectionId.value) return

  const collection = collections.value.find(c => c.id === selectedCollectionId.value)
  if (!collection) return

  const newRequest = {
    id: Date.now(),
    name: requestName.value.trim(),
    method: httpMethod.value,
    url: requestUrl.value,
    params: JSON.parse(JSON.stringify(requestParams.value)),
    headers: JSON.parse(JSON.stringify(requestHeaders.value)),
    auth: JSON.parse(JSON.stringify(requestAuth.value)),
    body: JSON.parse(JSON.stringify(requestBody.value)),
    createdAt: new Date().toISOString()
  }

  collection.requests.push(newRequest)
  
  // Save collections to localStorage
  localStorage.setItem('api-platform-collections', JSON.stringify(collections.value))
  
  showNotification(`Request saved to ${collection.name}`, 'success')
  emit('close')
}

const createNewCollection = () => {
  const name = prompt('Collection name:')
  if (name && name.trim()) {
    const newCollection = {
      id: Date.now(),
      name: name.trim(),
      description: '',
      requests: [],
      createdAt: new Date().toISOString()
    }
    
    collections.value.push(newCollection)
    selectedCollectionId.value = newCollection.id
    
    // Save collections to localStorage
    localStorage.setItem('api-platform-collections', JSON.stringify(collections.value))
    
    showNotification('Collection created', 'success')
  }
}

// Auto-select first collection if available
onMounted(() => {
  if (collections.value.length > 0) {
    selectedCollectionId.value = collections.value[0].id
  }
})
</script> 