import type { ToolConfig } from './index'
import { useCanvasStore } from '../../../stores/canvas'
import {
  renderInlineComponent,
  type VueComponentDefinition
} from '../../dynamicComponents'
import { getWindowDefinitions } from './canvasHandlers'
import { apiFetch } from '@/lib/tauri'

const API_URL = ''

export const fsComponentsApi = {
  async list(): Promise<VueComponentDefinition[]> {
    const res = await apiFetch(`${API_URL}/api/fs-components`)
    if (!res.ok) throw new Error(`Failed to list fs-components: ${res.statusText}`)
    return res.json()
  },

  async getByFolder(folder: string): Promise<VueComponentDefinition> {
    const res = await apiFetch(`${API_URL}/api/fs-components/${encodeURIComponent(folder)}`)
    if (!res.ok) throw new Error(`Component "${folder}" not found`)
    return res.json()
  }
}

function getCanvasContainer() {
  return document.getElementById('canvas-content')
}

function removePlaceholder(container: HTMLElement) {
  const placeholder = container.querySelector('.canvas-placeholder')
  if (placeholder) {
    placeholder.remove()
    window.dispatchEvent(new CustomEvent('canvas-content-rendered'))
  }
}

export function createFsComponentHandlers(): ToolConfig[] {
  return [
    {
      name: 'list_fs_components',
      description: 'Lista componentes Vue del filesystem (user-components/)',
      category: 'component',
      schema: {
        type: 'object',
        properties: {},
        required: []
      },
      handler: async () => {
        try {
          const components = await fsComponentsApi.list()
          if (components.length === 0) {
            return 'No hay componentes en user-components/. Crea una carpeta con un archivo .vue para empezar.'
          }
          const list = components.map(c => {
            const tags = c.tags?.length ? ` [${c.tags.join(', ')}]` : ''
            return `- ${c.folder}: ${c.name}${tags}`
          }).join('\n')
          return `Componentes en filesystem (${components.length}):\n${list}`
        } catch (e: any) {
          return `Error: ${e.message}`
        }
      }
    },
    {
      name: 'load_fs_component',
      description: 'Carga y renderiza un componente desde user-components/',
      category: 'component',
      schema: {
        type: 'object',
        properties: {
          folder: { type: 'string', description: 'Nombre de la carpeta del componente' },
          componentProps: { type: 'object', description: 'Props para el componente' },
          mode: { type: 'string', enum: ['replace', 'append'], description: 'Modo de renderizado' },
          x: { type: 'number', description: 'Posicion X inicial' },
          y: { type: 'number', description: 'Posicion Y inicial' },
          width: { type: 'number', description: 'Ancho inicial' },
          height: { type: 'number', description: 'Alto inicial' }
        },
        required: ['folder']
      },
      handler: async (args: { folder: string; componentProps?: Record<string, any>; mode?: string; x?: number; y?: number; width?: number; height?: number }) => {
        try {
          const definition = await fsComponentsApi.getByFolder(args.folder)

          const container = getCanvasContainer()
          if (!container) return 'Error: canvas no encontrado'

          removePlaceholder(container)

          const isAppend = args.mode === 'append'
          const layout = { x: args.x, y: args.y, width: args.width, height: args.height }
          const result = renderInlineComponent(definition, container, args.componentProps || {}, isAppend, layout)

          // Track definition for snapshot capture
          getWindowDefinitions().set(definition.id, {
            source: 'fs',
            componentId: args.folder,
            definition,
            componentProps: args.componentProps || {}
          })

          ;(window as any).__vueComponentUnmount = result.unmount

          const canvasStore = useCanvasStore()
          canvasStore.addToHistory({ tool: 'load_fs_component', args, timestamp: Date.now() })
          return `Componente "${definition.name}" cargado desde user-components/${args.folder}/`
        } catch (e: any) {
          return `Error: ${e.message}`
        }
      }
    }
  ]
}
