import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useApi } from '@/composables/useApi'
import type { PluginEntry } from '@/types'

export interface UmodPlugin {
  name: string
  title: string
  slug: string
  author: string
  description: string
  downloads: number
  downloads_shortened: string
  download_url: string
  latest_release_version: string
  latest_release_version_formatted: string
  icon_url: string
  url: string
  tags_all: string
  watchers_shortened: string
  created_at: string
  updated_at: string
}

export interface UmodBrowseResult {
  current_page: number
  data: UmodPlugin[]
  last_page: number
  per_page: number
  total: number
}

export const usePluginStore = defineStore('plugins', () => {
  const plugins = ref<PluginEntry[]>([])
  const searchResults = ref<any[]>([])
  const browseResults = ref<UmodBrowseResult | null>(null)
  const isLoading = ref(false)
  const isBrowseLoading = ref(false)
  const api = useApi()

  async function fetchPlugins() {
    isLoading.value = true
    try {
      plugins.value = await api.get<PluginEntry[]>('/plugins')
    } finally {
      isLoading.value = false
    }
  }

  async function installPlugin(data: { plugin_name: string; umod_slug?: string; source: string }) {
    await api.post('/plugins/install', data)
    await fetchPlugins()
  }

  async function uninstallPlugin(id: string) {
    await api.del(`/plugins/${id}`)
    await fetchPlugins()
  }

  async function reloadPlugin(id: string) {
    await api.post(`/plugins/${id}/reload`, {})
  }

  async function updatePluginConfig(id: string, config: Record<string, any>) {
    await api.put(`/plugins/${id}/config`, { config })
    await fetchPlugins()
  }

  // Legacy — kept for backwards compatibility, routes to browse
  async function searchPlugins(query: string) {
    isLoading.value = true
    try {
      searchResults.value = await api.get<any[]>(`/plugins/search?q=${encodeURIComponent(query)}`)
    } finally {
      isLoading.value = false
    }
  }

  async function browseUmod(query: string, page = 1, sort = 'downloads') {
    isBrowseLoading.value = true
    try {
      const params = new URLSearchParams({ page: String(page), sort })
      if (query.trim()) params.set('query', query.trim())
      browseResults.value = await api.get<UmodBrowseResult>(`/plugins/browse?${params.toString()}`)
    } finally {
      isBrowseLoading.value = false
    }
  }

  async function uploadPlugin(file: File): Promise<PluginEntry> {
    const formData = new FormData()
    formData.append('file', file)
    const result = await api.upload<PluginEntry>('/plugins/upload', formData)
    await fetchPlugins()
    return result
  }

  return {
    plugins,
    searchResults,
    browseResults,
    isLoading,
    isBrowseLoading,
    fetchPlugins,
    installPlugin,
    uninstallPlugin,
    reloadPlugin,
    updatePluginConfig,
    searchPlugins,
    browseUmod,
    uploadPlugin,
  }
})
