import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Prompt } from '@/types/prompt'
import { API } from '@/Api'

export const usePromptStore = defineStore('prompt', () => {
  // State
  const promptTemplates = ref<Prompt[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const isLoaded = ref(false)

  // Actions
  async function loadTemplates() {
    // Don't reload if already loaded
    if (isLoaded.value) {
      return
    }

    loading.value = true
    error.value = null

    try {
      const response = await API.getPromptsLibraryForUsers()
      promptTemplates.value = response.data.prompts || []
      isLoaded.value = true
    } catch (err: any) {
      error.value = err.message || 'Failed to load prompt templates'
      console.error('Error loading prompt templates:', err)
      promptTemplates.value = []
    } finally {
      loading.value = false
    }
  }

  function getTemplatesByCategory(category: string): Prompt[] {
    return promptTemplates.value?.filter((template) => template.category === category) || []
  }

  function searchTemplates(query: string): Prompt[] {
    if (!promptTemplates.value) return []

    if (!query.trim()) {
      return promptTemplates.value
    }

    const searchTerm = query.toLowerCase()
    return promptTemplates.value.filter(
      (template) =>
        template.name.toLowerCase().includes(searchTerm) ||
        template.description.toLowerCase().includes(searchTerm) ||
        template.prompt.toLowerCase().includes(searchTerm)
    )
  }

  function getTemplateById(id: string): Prompt | undefined {
    return promptTemplates.value?.find((template) => template.id === id)
  }

  // Reset state (useful for testing or when switching contexts)
  function reset() {
    promptTemplates.value = []
    loading.value = false
    error.value = null
    isLoaded.value = false
  }

  return {
    // State
    promptTemplates,
    loading,
    error,
    isLoaded,

    // Actions
    loadTemplates,
    getTemplatesByCategory,
    searchTemplates,
    getTemplateById,
    reset,
  }
})
