<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useComponentsStore, type ComponentState } from '../stores/components'
import { useRouter } from 'vue-router'

const store = useComponentsStore()
const router = useRouter()

const searchQuery = ref('')
const selectedComponent = ref<ComponentState | null>(null)
const viewMode = ref<'grid' | 'list'>('grid')
const showDeleteConfirm = ref(false)
const componentToDelete = ref<string | null>(null)

const filteredComponents = computed(() => {
  if (!searchQuery.value) return store.savedComponents
  const query = searchQuery.value.toLowerCase()
  return store.savedComponents.filter(c =>
    c.name.toLowerCase().includes(query) ||
    c.id.toLowerCase().includes(query)
  )
})

function selectComponent(comp: ComponentState) {
  selectedComponent.value = comp
}

function loadInCanvas(comp: ComponentState) {
  window.dispatchEvent(new CustomEvent('load-vue-component', {
    detail: {
      id: comp.id,
      name: comp.name,
      template: comp.template,
      setup: comp.setup,
      style: comp.style,
      props: typeof comp.props === 'string' ? JSON.parse(comp.props) : comp.props || [],
      imports: typeof comp.imports === 'string' ? JSON.parse(comp.imports) : comp.imports || []
    }
  }))
  router.push('/')
}

function confirmDelete(id: string) {
  componentToDelete.value = id
  showDeleteConfirm.value = true
}

async function deleteComponent() {
  if (componentToDelete.value) {
    await store.deleteComponent(componentToDelete.value)
    if (selectedComponent.value?.id === componentToDelete.value) {
      selectedComponent.value = null
    }
  }
  showDeleteConfirm.value = false
  componentToDelete.value = null
}

async function deleteAll() {
  if (confirm('¿Eliminar TODOS los componentes? Esta acción no se puede deshacer.')) {
    await store.deleteAllComponents()
    selectedComponent.value = null
  }
}

function formatDate(dateStr?: string) {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString()
}

function copyToClipboard(text: string) {
  navigator.clipboard.writeText(text)
}

onMounted(() => {
  store.fetchComponents()
})
</script>

<template>
  <div class="components-page">
    <!-- Sidebar con lista -->
    <aside class="sidebar">
      <div class="sidebar-header">
        <h2>Componentes</h2>
        <span class="count">{{ store.savedCount }}</span>
      </div>

      <div class="search-box">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="11" cy="11" r="8"/>
          <path d="m21 21-4.3-4.3"/>
        </svg>
        <input v-model="searchQuery" placeholder="Buscar componentes..." />
      </div>

      <div class="view-toggle">
        <button :class="{ active: viewMode === 'grid' }" @click="viewMode = 'grid'" title="Vista grid">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/>
            <rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/>
          </svg>
        </button>
        <button :class="{ active: viewMode === 'list' }" @click="viewMode = 'list'" title="Vista lista">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/>
          </svg>
        </button>
      </div>

      <div class="components-list" :class="viewMode">
        <div v-if="store.loading" class="loading">Cargando...</div>
        <div v-else-if="filteredComponents.length === 0" class="empty">
          <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1">
            <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
          </svg>
          <p>No hay componentes</p>
        </div>
        <template v-else>
          <div
            v-for="comp in filteredComponents"
            :key="comp.id"
            class="component-card"
            :class="{ selected: selectedComponent?.id === comp.id }"
            @click="selectComponent(comp)"
          >
            <div class="card-icon">
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
              </svg>
            </div>
            <div class="card-info">
              <span class="card-name">{{ comp.name }}</span>
              <span class="card-id">{{ comp.id }}</span>
            </div>
            <div class="card-actions">
              <button class="action-btn load" @click.stop="loadInCanvas(comp)" title="Cargar en canvas">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <polygon points="5 3 19 12 5 21 5 3"/>
                </svg>
              </button>
              <button class="action-btn delete" @click.stop="confirmDelete(comp.id)" title="Eliminar">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/>
                  <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>
                </svg>
              </button>
            </div>
          </div>
        </template>
      </div>

      <div class="sidebar-footer">
        <button class="btn-danger" @click="deleteAll" :disabled="store.savedCount === 0">
          Eliminar todos
        </button>
      </div>
    </aside>

    <!-- Panel de detalles -->
    <main class="details-panel">
      <div v-if="!selectedComponent" class="no-selection">
        <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1">
          <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
          <polyline points="3.29 7 12 12 20.71 7"/>
          <line x1="12" y1="22" x2="12" y2="12"/>
        </svg>
        <h3>Selecciona un componente</h3>
        <p>Haz clic en un componente de la lista para ver sus detalles</p>
      </div>

      <template v-else>
        <div class="details-header">
          <div class="details-title">
            <h2>{{ selectedComponent.name }}</h2>
            <code>{{ selectedComponent.id }}</code>
          </div>
          <div class="details-actions">
            <button class="btn-primary" @click="loadInCanvas(selectedComponent)">
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polygon points="5 3 19 12 5 21 5 3"/>
              </svg>
              Cargar en Canvas
            </button>
            <button class="btn-danger" @click="confirmDelete(selectedComponent.id)">
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/>
              </svg>
              Eliminar
            </button>
          </div>
        </div>

        <div class="details-meta">
          <div class="meta-item">
            <span class="meta-label">Creado</span>
            <span class="meta-value">{{ formatDate(selectedComponent.created_at) }}</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">Actualizado</span>
            <span class="meta-value">{{ formatDate(selectedComponent.updated_at) }}</span>
          </div>
          <div class="meta-item" v-if="selectedComponent.imports">
            <span class="meta-label">Imports</span>
            <span class="meta-value">{{ Array.isArray(selectedComponent.imports) ? selectedComponent.imports.join(', ') : selectedComponent.imports }}</span>
          </div>
        </div>

        <div class="code-sections">
          <div class="code-section">
            <div class="code-header">
              <span>Template</span>
              <button @click="copyToClipboard(selectedComponent.template)" title="Copiar">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
                  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
                </svg>
              </button>
            </div>
            <pre><code>{{ selectedComponent.template }}</code></pre>
          </div>

          <div class="code-section" v-if="selectedComponent.setup">
            <div class="code-header">
              <span>Setup</span>
              <button @click="copyToClipboard(selectedComponent.setup)" title="Copiar">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
                  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
                </svg>
              </button>
            </div>
            <pre><code>{{ selectedComponent.setup }}</code></pre>
          </div>

          <div class="code-section" v-if="selectedComponent.style">
            <div class="code-header">
              <span>Style</span>
              <button @click="copyToClipboard(selectedComponent.style)" title="Copiar">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
                  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
                </svg>
              </button>
            </div>
            <pre><code>{{ selectedComponent.style }}</code></pre>
          </div>
        </div>
      </template>
    </main>

    <!-- Modal de confirmación -->
    <div v-if="showDeleteConfirm" class="modal-overlay" @click="showDeleteConfirm = false">
      <div class="modal" @click.stop>
        <h3>¿Eliminar componente?</h3>
        <p>Esta acción no se puede deshacer.</p>
        <div class="modal-actions">
          <button class="btn-secondary" @click="showDeleteConfirm = false">Cancelar</button>
          <button class="btn-danger" @click="deleteComponent">Eliminar</button>
        </div>
      </div>
    </div>
  </div>
</template>

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

/* Sidebar */
.sidebar {
  width: 320px;
  background: var(--bg-secondary);
  border-right: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1.25rem;
  border-bottom: 1px solid var(--border-color);
}

.sidebar-header h2 {
  margin: 0;
  font-size: 1.125rem;
  color: var(--text-primary);
}

.count {
  background: var(--bg-hover);
  padding: 0.25rem 0.75rem;
  border-radius: 9999px;
  font-size: 0.75rem;
  color: var(--text-secondary);
}

.search-box {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin: 1rem;
  padding: 0.625rem 0.875rem;
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 8px;
}

.search-box svg {
  color: var(--text-secondary);
  flex-shrink: 0;
}

.search-box input {
  flex: 1;
  background: transparent;
  border: none;
  color: var(--text-primary);
  font-size: 0.875rem;
  outline: none;
}

.search-box input::placeholder {
  color: var(--text-muted);
}

.view-toggle {
  display: flex;
  gap: 0.25rem;
  padding: 0 1rem;
  margin-bottom: 0.5rem;
}

.view-toggle button {
  padding: 0.5rem;
  background: transparent;
  border: none;
  color: var(--text-secondary);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.15s;
}

.view-toggle button:hover {
  background: var(--bg-hover);
  color: var(--text-primary);
}

.view-toggle button.active {
  background: var(--bg-hover);
  color: #6366f1;
}

.components-list {
  flex: 1;
  overflow-y: auto;
  padding: 0.5rem 1rem;
}

.components-list.grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 0.75rem;
}

.components-list.grid .component-card {
  flex-direction: column;
  text-align: center;
  padding: 1rem;
}

.components-list.grid .card-icon {
  margin-bottom: 0.5rem;
}

.components-list.grid .card-actions {
  margin-top: 0.75rem;
  justify-content: center;
}

.loading, .empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 2rem;
  color: var(--text-muted);
  text-align: center;
  grid-column: 1 / -1;
}

.empty svg {
  opacity: 0.3;
  margin-bottom: 1rem;
}

.component-card {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem;
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.15s;
}

.component-card:hover {
  border-color: #6366f1;
  background: rgba(99, 102, 241, 0.05);
}

.component-card.selected {
  border-color: #6366f1;
  background: rgba(99, 102, 241, 0.1);
}

.card-icon {
  color: #6366f1;
}

.card-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 0.125rem;
}

.card-name {
  font-weight: 500;
  color: var(--text-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-id {
  font-size: 0.7rem;
  color: var(--text-secondary);
  font-family: monospace;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-actions {
  display: flex;
  gap: 0.25rem;
}

.action-btn {
  padding: 0.375rem;
  background: transparent;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  color: var(--text-secondary);
  transition: all 0.15s;
}

.action-btn:hover {
  transform: scale(1.1);
}

.action-btn.load:hover {
  background: rgba(34, 197, 94, 0.2);
  color: #22c55e;
}

.action-btn.delete:hover {
  background: rgba(239, 68, 68, 0.2);
  color: #ef4444;
}

.sidebar-footer {
  padding: 1rem;
  border-top: 1px solid var(--border-color);
}

/* Details Panel */
.details-panel {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
}

.no-selection {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--text-muted);
  text-align: center;
}

.no-selection svg {
  opacity: 0.3;
  margin-bottom: 1rem;
}

.no-selection h3 {
  margin: 0 0 0.5rem 0;
  color: var(--text-secondary);
}

.details-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1.5rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid var(--border-color);
}

.details-title h2 {
  margin: 0 0 0.5rem 0;
  color: var(--text-primary);
}

.details-title code {
  font-size: 0.8rem;
  color: var(--text-secondary);
  background: var(--bg-hover);
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
}

.details-actions {
  display: flex;
  gap: 0.75rem;
}

.details-meta {
  display: flex;
  gap: 2rem;
  margin-bottom: 1.5rem;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.meta-label {
  font-size: 0.7rem;
  text-transform: uppercase;
  color: var(--text-muted);
  letter-spacing: 0.05em;
}

.meta-value {
  font-size: 0.875rem;
  color: var(--text-secondary);
}

.code-sections {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.code-section {
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  overflow: hidden;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.625rem 1rem;
  background: var(--bg-hover);
  border-bottom: 1px solid var(--border-color);
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: uppercase;
  color: var(--text-secondary);
}

.code-header button {
  padding: 0.25rem;
  background: transparent;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.15s;
}

.code-header button:hover {
  background: var(--bg-secondary);
  color: var(--text-primary);
}

.code-section pre {
  margin: 0;
  padding: 1rem;
  overflow-x: auto;
  max-height: 300px;
}

.code-section code {
  font-family: 'JetBrains Mono', 'Fira Code', monospace;
  font-size: 0.8rem;
  color: var(--text-primary);
  white-space: pre-wrap;
  word-break: break-word;
}

/* Buttons */
.btn-primary {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.625rem 1rem;
  background: #6366f1;
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.15s;
}

.btn-primary:hover {
  background: #4f46e5;
}

.btn-secondary {
  padding: 0.625rem 1rem;
  background: var(--bg-hover);
  color: var(--text-primary);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.15s;
}

.btn-secondary:hover {
  background: var(--bg-tertiary);
}

.btn-danger {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.625rem 1rem;
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
  border: 1px solid rgba(239, 68, 68, 0.3);
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.15s;
}

.btn-danger:hover {
  background: rgba(239, 68, 68, 0.2);
}

.btn-danger:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* Modal */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 12px;
  padding: 1.5rem;
  min-width: 300px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
}

.modal h3 {
  margin: 0 0 0.5rem 0;
  color: var(--text-primary);
}

.modal p {
  margin: 0 0 1.5rem 0;
  color: var(--text-secondary);
}

.modal-actions {
  display: flex;
  gap: 0.75rem;
  justify-content: flex-end;
}
</style>
