<template>
  <div class="space-y-4">
    <!-- Add External Source -->
    <div class="settings-row border-b border-gray-100 py-4">
      <div class="settings-label">
        <FormLabel
          :title="$t('Add External Source')"
          :help="$t('Add external URLs with title and context to expand your knowledge base')"
        />
      </div>
      <div class="settings-control">
        <div class="space-y-3 w-full">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
            <FormInput
              v-model="newSource.title"
              type="text"
              placeholder="Source Title (e.g., Documentation)"
              class="w-full"
            />
            <FormInput
              v-model="newSource.link"
              type="url"
              placeholder="https://example.com/knowledge-base"
              class="w-full"
            />
          </div>
          <FormInput
            v-model="newSource.context"
            type="textarea"
            placeholder="Context or description of this source (optional)"
            :rows="2"
            class="w-full"
          />
          <div class="flex justify-end">
            <BaseButton
              variant="success"
              :loading="state.loading.adding"
              :disabled="!newSource.title || !newSource.link || state.loading.adding"
              @click="addExternalSource"
            >
              {{ $t('Add Source') }}
            </BaseButton>
          </div>
        </div>
      </div>
    </div>

    <!-- External Sources List (shown when has sources) -->
    <div v-if="form.external_sources && form.external_sources.length > 0" class="settings-row border-b border-gray-100 py-4">
      <div class="settings-label">
        <FormLabel
          :title="$t('External Sources')"
          :help="$t('Manage your external knowledge sources')"
        />
      </div>
      <div class="settings-control">
        <div class="space-y-3 w-full">
          <div
            v-for="(source, index) in form.external_sources"
            :key="index"
            class="border border-gray-200 rounded-lg p-4 bg-gray-50"
          >
            <div class="flex items-start justify-between">
              <div class="flex-1">
                <h4 class="font-medium text-gray-900 mb-1">{{ source.title }}</h4>
                <a :href="source.link" target="_blank" class="text-blue-600 hover:text-blue-800 text-sm break-all">
                  {{ source.link }}
                </a>
                <p v-if="source.context" class="text-gray-600 text-sm mt-2">{{ source.context }}</p>
              </div>
              <div class="flex items-center gap-2 ml-3">
                <button
                  type="button"
                  @click="editExternalSource(source, index)"
                  class="text-blue-600 hover:text-blue-800 p-1"
                  :title="$t('Edit source')"
                >
                  <Icon icon="material-symbols:edit-outline" class="w-4 h-4" />
                </button>
                <button
                  type="button"
                  @click="removeExternalSource(source.link, index)"
                  class="text-red-600 hover:text-red-800 p-1"
                  :title="$t('Remove source')"
                >
                  <Icon icon="material-symbols:delete-outline" class="w-4 h-4" />
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>





    <!-- Edit Source Modal -->
    <div v-if="state.editingSource" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg p-6 w-full max-w-md mx-4">
        <h3 class="text-lg font-medium text-gray-900 mb-4">{{ $t('Edit External Source') }}</h3>

        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">{{ $t('Source Title') }}</label>
            <FormInput
              v-model="editForm.title"
              type="text"
              placeholder="e.g. Documentation"
              class="w-full"
            />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">{{ $t('Source URL') }}</label>
            <FormInput
              v-model="editForm.link"
              type="url"
              placeholder="https://example.com/knowledge-base"
              class="w-full"
            />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">{{ $t('Context (Optional)') }}</label>
            <FormInput
              v-model="editForm.context"
              type="textarea"
              placeholder="Context or description of this source"
              :rows="3"
              class="w-full"
            />
          </div>
        </div>

        <div class="flex justify-end gap-3 mt-6">
          <BaseButton
            variant="secondary"
            @click="cancelEdit"
          >
            {{ $t('Cancel') }}
          </BaseButton>
          <BaseButton
            variant="primary"
            :loading="state.loading.updating"
            :disabled="!editForm.title || !editForm.link || state.loading.updating"
            @click="updateExternalSource"
          >
            {{ $t('Update Source') }}
          </BaseButton>
        </div>
      </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <DeleteConfirmationModal
      v-model="deleteConfirmation.isVisible.value"
      :title="deleteConfirmation.modalConfig.value.title"
      :message="deleteConfirmation.modalConfig.value.message"
      :details="deleteConfirmation.modalConfig.value.details"
      :confirm-text="deleteConfirmation.modalConfig.value.confirmText"
      :cancel-text="deleteConfirmation.modalConfig.value.cancelText"
      :loading="deleteConfirmation.isLoading.value"
      @confirm="deleteConfirmation.handleConfirm"
      @cancel="deleteConfirmation.handleCancel"
    />
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { Icon } from '@iconify/vue'
import DeleteConfirmationModal from '@/Admin/Components/DeleteConfirmationModal.vue'
import FormLabel from '@/Admin/Components/FormLabel.vue'
import FormInput from '@/Admin/Components/FormInput.vue'
import BaseButton from '@/Admin/Components/BaseButton.vue'

import { useForm } from '@/Admin/js/composables/useForm.js'
import { useDeleteConfirmation } from '@/Admin/js/composables/useDeleteConfirmation.js'
import { useToast } from '@/Admin/js/composables/useToast.js'
import Http from '@/Admin/js/utils/http.js'

// Reactive state
const state = reactive({
    loading: {
        page: false,
        adding: false,
        updating: false
    },
    editingSource: null,
    editingIndex: -1
})

// Toast notifications
const { showSuccess, showError } = useToast()

// Delete confirmation modal
const deleteConfirmation = useDeleteConfirmation()

// New external source form
const newSource = ref({
  title: '',
  link: '',
  context: ''
})

// Edit form
const editForm = ref({
  title: '',
  link: '',
  context: ''
})

// Form defaults for external sources
const makeDefaults = () => ({
  external_sources: []
})

// Initialize form
const form = useForm(makeDefaults())

// API calls
const loadSettings = async () => {
  try {
    state.loading.page = true
    const response = await Http.get('data-source-settings')

    if (response.success) {
      // Update form with data from API (only external sources related)
      form.fill({
        external_sources: response.data.external_sources || []
      })
    }
  } catch (error) {
    console.error('Error loading settings:', error)
  } finally {
    state.loading.page = false
  }
}



// Actions
const addExternalSource = async () => {
  if (!newSource.value.title || !newSource.value.link) {
    showError('Missing information', 'Please provide both title and URL')
    return
  }

  state.loading.adding = true
  try {
    const response = await Http.post('data-source-settings/add-external-source', newSource.value)

    if (response.success) {
      // Add to local form data
      if (!form.external_sources) {
        form.external_sources = []
      }
      form.external_sources.push({ ...newSource.value })

      // Reset form
      newSource.value = { title: '', link: '', context: '' }

      showSuccess('Source added successfully!', `"${newSource.value.title}" has been added to your knowledge base`)
    } else {
      showError('Failed to add source', response.message || 'Please try again')
    }
  } catch (error) {
    console.error('Error adding external source:', error)
    showError('Failed to add source', 'An unexpected error occurred')
  } finally {
    state.loading.adding = false
  }
}

// Edit external source
const editExternalSource = (source, index) => {
  state.editingSource = source
  state.editingIndex = index
  editForm.value = { ...source }
}

const updateExternalSource = async () => {
  if (!editForm.value.title || !editForm.value.link) {
    showError('Missing information', 'Please provide both title and URL')
    return
  }

  state.loading.updating = true
  try {
    const response = await Http.put('data-source-settings/update-external-source', {
      old_link: state.editingSource.link,
      ...editForm.value
    })

    if (response.success) {
      // Update local form data
      form.external_sources[state.editingIndex] = { ...editForm.value }

      // Close modal
      cancelEdit()

      showSuccess('Source updated successfully!')
    } else {
      showError('Failed to update source', response.message || 'Please try again')
    }
  } catch (error) {
    console.error('Error updating external source:', error)
    showError('Failed to update source', 'An unexpected error occurred')
  } finally {
    state.loading.updating = false
  }
}

const cancelEdit = () => {
  state.editingSource = null
  state.editingIndex = -1
  editForm.value = { title: '', link: '', context: '' }
}

// Remove external source
const removeExternalSource = (link, index) => {
  const source = form.external_sources[index]

  deleteConfirmation.showDeleteConfirmation({
    title: 'Remove External Source',
    message: `Are you sure you want to remove "${source.title}"?`,
    details: 'This external source will no longer be available to your AI chatbot. This action cannot be undone.',
    confirmText: 'Remove Source',
    cancelText: 'Cancel',
    onConfirm: async () => {
      try {
        const response = await Http.delete('data-source-settings/remove-external-source', { link })

        if (response.success) {
          // Remove from local form data
          form.external_sources.splice(index, 1)

          showSuccess('Source removed successfully!', `"${source.title}" has been removed from your knowledge base`)
        } else {
          showError('Failed to remove source', response.message || 'Please try again')
          throw new Error(response.message || 'Failed to remove external source')
        }
      } catch (error) {
        console.error('Error removing external source:', error)
        throw error // Re-throw to keep modal open on error
      }
    }
  })
}

// Load data on mount
onMounted(() => {
  loadSettings()
})
</script>

<style lang="scss" scoped>
/* Settings two-column row layout - matching other settings pages */
.settings-row {
  @apply grid grid-cols-1 md:grid-cols-12 items-center gap-6;
}

.settings-label {
  @apply md:col-span-5 flex flex-col justify-center;
}

.settings-control {
  @apply md:col-span-7 flex items-center;
}

.label-title {
  @apply text-sm md:text-base font-medium text-gray-800;
}

.label-help {
  @apply text-xs text-gray-500 mt-1;
}
</style>
