<script setup lang="ts">
import { onMounted, onUnmounted, ref, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { renderInlineComponent, type VueComponentDefinition } from '../services/dynamicComponents'
import { useProjectCanvasStore } from '../stores/projectCanvas'
import { useCanvasStore } from '../stores/canvas'
import { useThemeStore } from '../stores/theme'

const props = defineProps<{
  id: string
}>()

const router = useRouter()
const projectCanvasStore = useProjectCanvasStore()
const canvasStore = useCanvasStore()
const themeStore = useThemeStore()

const loading = ref(true)
const error = ref<string | null>(null)

async function loadCanvas() {
  loading.value = true
  error.value = null

  const success = await projectCanvasStore.activateCanvas(props.id)

  if (!success) {
    error.value = 'Canvas no encontrado'
    loading.value = false
    return
  }

  // Apply canvas theme if set
  const canvas = projectCanvasStore.activeCanvas
  if (canvas?.theme_id) {
    const theme = themeStore.themes.find(t => t.id === canvas.theme_id)
    if (theme) {
      themeStore.applyTheme(theme.variables)
    }
  }

  // Set loading to false first, then render after DOM updates
  loading.value = false

  // Wait for DOM to update with canvas-content element
  await nextTick()

  // Render all components
  const container = document.getElementById('canvas-content')
  if (container && projectCanvasStore.activeCanvasComponents.length > 0) {
    container.innerHTML = ''

    for (const canvasComp of projectCanvasStore.activeCanvasComponents) {
      if (!canvasComp.isVisible || !canvasComp.component) continue

      const definition: VueComponentDefinition = {
        id: canvasComp.component.id,
        name: canvasComp.component.name,
        template: canvasComp.component.template,
        setup: canvasComp.component.setup,
        style: canvasComp.component.style,
        props: canvasComp.component.props,
        imports: canvasComp.component.imports || ['ref', 'reactive', 'computed']
      }

      const componentProps = { ...canvasComp.props }
      renderInlineComponent(definition, container, componentProps, true)
    }
  }
}

function handleLoadComponent(e: Event) {
  const detail = (e as CustomEvent).detail
  if (!detail) return

  const container = document.getElementById('canvas-content')
  if (!container) return

  const placeholder = container.querySelector('.canvas-placeholder')
  if (placeholder) placeholder.remove()

  const definition: VueComponentDefinition = {
    id: detail.id,
    name: detail.name,
    template: detail.template,
    setup: detail.setup,
    style: detail.style,
    props: detail.props,
    imports: detail.imports || ['ref', 'reactive', 'computed']
  }

  const result = renderInlineComponent(definition, container, {}, true)
  ;(window as any).__vueComponentUnmount = result.unmount

  window.dispatchEvent(new CustomEvent('vue-component-rendered', { detail }))
  canvasStore.addToHistory({ tool: 'load_vue_component', args: detail, timestamp: Date.now() })
}

function goBack() {
  router.push('/dynamic/canvas')
}

onMounted(() => {
  loadCanvas()
  window.addEventListener('load-vue-component', handleLoadComponent)
})

onUnmounted(() => {
  window.removeEventListener('load-vue-component', handleLoadComponent)
  projectCanvasStore.clearActiveCanvas()
})

watch(() => props.id, () => {
  loadCanvas()
})
</script>

<template>
  <div class="project-canvas-page">
    <div class="canvas-container">
      <div v-if="loading" class="canvas-loading">
        <div class="spinner"></div>
        <p>Cargando canvas...</p>
      </div>

      <div v-else-if="error" class="canvas-error">
        <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
          <circle cx="12" cy="12" r="10"/>
          <path d="M12 8v4"/>
          <path d="M12 16h.01"/>
        </svg>
        <p>{{ error }}</p>
        <button @click="goBack">Volver a proyectos</button>
      </div>

      <div v-else id="canvas-content" class="canvas-content">
        <div v-if="projectCanvasStore.activeCanvasComponents.length === 0" class="canvas-placeholder">
          <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
            <rect x="3" y="3" width="18" height="18" rx="2"/>
            <path d="M3 9h18"/>
            <path d="M9 21V9"/>
          </svg>
          <p>Canvas vacio</p>
          <span>Usa las herramientas MCP para agregar componentes</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.project-canvas-page {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--bg-primary);
  overflow: hidden;
}

.canvas-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: auto;
}

.canvas-content {
  flex: 1;
  padding: 1.5rem;
  min-height: 100%;
}

.canvas-loading,
.canvas-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 400px;
  color: var(--text-muted);
  text-align: center;
  gap: 1rem;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 3px solid var(--border-color);
  border-top-color: var(--accent);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.canvas-error svg {
  color: var(--error);
  opacity: 0.7;
}

.canvas-error button {
  padding: 0.5rem 1rem;
  background: var(--accent);
  color: var(--accent-text);
  border: none;
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: background 0.15s ease;
}

.canvas-error button:hover {
  background: var(--accent-hover);
}

.canvas-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 400px;
  color: var(--text-muted);
  text-align: center;
}

.canvas-placeholder svg {
  margin-bottom: 1rem;
  opacity: 0.5;
}

.canvas-placeholder p {
  font-size: 1.25rem;
  margin: 0 0 0.5rem 0;
}

.canvas-placeholder span {
  font-size: 0.875rem;
  opacity: 0.7;
}
</style>
