import type { ToolConfig } from './index'
import { useProjectCanvasStore } from '../../../stores/projectCanvas'

export function createProjectCanvasHandlers(): ToolConfig[] {
  return [
    {
      name: 'list_canvases',
      description: 'Lista todos los canvas disponibles',
      category: 'project',
      schema: {
        type: 'object',
        properties: {
          type: { type: 'string', enum: ['all', 'project', 'system'], description: 'Filtrar por tipo' },
          include_archived: { type: 'boolean', description: 'Incluir canvases archivados' }
        }
      },
      handler: async (args: { type?: string; include_archived?: boolean }) => {
        const store = useProjectCanvasStore()
        await store.fetchCanvases(args.include_archived || false)
        let canvases = store.canvases

        if (args.type === 'project') {
          canvases = store.projectCanvases
        } else if (args.type === 'system') {
          canvases = store.systemCanvases
        }

        return JSON.stringify(canvases.map(c => ({
          id: c.id,
          name: c.name,
          type: c.type,
          status: c.status,
          description: c.description
        })), null, 2)
      }
    },
    {
      name: 'create_canvas',
      description: 'Crea un nuevo canvas',
      category: 'project',
      schema: {
        type: 'object',
        properties: {
          name: { type: 'string', description: 'Nombre del canvas' },
          description: { type: 'string', description: 'Descripcion' },
          theme_id: { type: 'string', description: 'ID del tema' },
          config: { type: 'object', description: 'Configuracion' }
        },
        required: ['name']
      },
      handler: async (args: { name: string; description?: string; theme_id?: string; config?: object }) => {
        const store = useProjectCanvasStore()
        const id = await store.createCanvas({
          name: args.name,
          description: args.description,
          theme_id: args.theme_id,
          config: args.config as any,
          type: 'project'
        })

        if (id) {
          return `Canvas "${args.name}" creado. ID: ${id}`
        }
        return `Error: ${store.error}`
      }
    },
    {
      name: 'get_canvas',
      description: 'Obtiene detalles de un canvas',
      category: 'project',
      schema: {
        type: 'object',
        properties: {
          id: { type: 'string', description: 'ID del canvas' }
        },
        required: ['id']
      },
      handler: async (args: { id: string }) => {
        const store = useProjectCanvasStore()
        const canvas = await store.fetchCanvasById(args.id)
        if (!canvas) {
          return `Canvas "${args.id}" no encontrado`
        }
        return JSON.stringify(canvas, null, 2)
      }
    },
    {
      name: 'update_canvas',
      description: 'Actualiza un canvas existente',
      category: 'project',
      schema: {
        type: 'object',
        properties: {
          id: { type: 'string', description: 'ID del canvas' },
          name: { type: 'string', description: 'Nuevo nombre' },
          description: { type: 'string', description: 'Nueva descripcion' },
          theme_id: { type: 'string', description: 'Nuevo tema' },
          config: { type: 'object', description: 'Nueva configuracion' }
        },
        required: ['id']
      },
      handler: async (args: { id: string; name?: string; description?: string; theme_id?: string; config?: object }) => {
        const store = useProjectCanvasStore()
        const { id, ...data } = args
        const success = await store.updateCanvas(id, data as any)

        if (success) {
          return `Canvas "${id}" actualizado`
        }
        return `Error: ${store.error}`
      }
    },
    {
      name: 'delete_canvas',
      description: 'Archiva un canvas (soft delete)',
      category: 'project',
      schema: {
        type: 'object',
        properties: {
          id: { type: 'string', description: 'ID del canvas' }
        },
        required: ['id']
      },
      handler: async (args: { id: string }) => {
        const store = useProjectCanvasStore()
        const success = await store.deleteCanvas(args.id)

        if (success) {
          return `Canvas "${args.id}" archivado`
        }
        return `Error: ${store.error}`
      }
    },
    {
      name: 'clone_canvas',
      description: 'Clona un canvas existente',
      category: 'project',
      schema: {
        type: 'object',
        properties: {
          id: { type: 'string', description: 'ID del canvas a clonar' },
          name: { type: 'string', description: 'Nombre para el nuevo canvas' }
        },
        required: ['id']
      },
      handler: async (args: { id: string; name?: string }) => {
        const store = useProjectCanvasStore()
        const newId = await store.cloneCanvas(args.id, args.name)

        if (newId) {
          return `Canvas clonado. Nuevo ID: ${newId}`
        }
        return `Error: ${store.error}`
      }
    },
    {
      name: 'add_component_to_canvas',
      description: 'Agrega un componente a un canvas',
      category: 'project',
      schema: {
        type: 'object',
        properties: {
          canvas_id: { type: 'string', description: 'ID del canvas' },
          component_id: { type: 'string', description: 'ID del componente' },
          props: { type: 'object', description: 'Props para el componente' },
          position: { type: 'number', description: 'Posicion' }
        },
        required: ['canvas_id', 'component_id']
      },
      handler: async (args: { canvas_id: string; component_id: string; props?: object; position?: number }) => {
        const store = useProjectCanvasStore()
        const success = await store.addComponentToCanvas(
          args.canvas_id,
          args.component_id,
          args.props as Record<string, any>,
          args.position
        )

        if (success) {
          return `Componente agregado al canvas`
        }
        return 'Error al agregar componente'
      }
    },
    {
      name: 'remove_component_from_canvas',
      description: 'Remueve un componente de un canvas',
      category: 'project',
      schema: {
        type: 'object',
        properties: {
          canvas_id: { type: 'string', description: 'ID del canvas' },
          component_id: { type: 'string', description: 'ID del componente' }
        },
        required: ['canvas_id', 'component_id']
      },
      handler: async (args: { canvas_id: string; component_id: string }) => {
        const store = useProjectCanvasStore()
        const success = await store.removeComponentFromCanvas(args.canvas_id, args.component_id)

        if (success) {
          return `Componente removido del canvas`
        }
        return 'Error al remover componente'
      }
    },
    {
      name: 'get_canvas_components',
      description: 'Obtiene los componentes de un canvas',
      category: 'project',
      schema: {
        type: 'object',
        properties: {
          canvas_id: { type: 'string', description: 'ID del canvas' }
        },
        required: ['canvas_id']
      },
      handler: async (args: { canvas_id: string }) => {
        const store = useProjectCanvasStore()
        await store.fetchCanvasComponents(args.canvas_id)
        return JSON.stringify(store.activeCanvasComponents, null, 2)
      }
    }
  ]
}
