<template>
  <AppLayout>
    <div class="qrcodes-page">
      <header class="page-header">
        <div>
          <h1>QR Codes</h1>
          <p class="subtitle">Design and manage your QR codes</p>
        </div>
        <router-link to="/qrcodes/new" class="cta">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <line x1="12" y1="5" x2="12" y2="19"/>
            <line x1="5" y1="12" x2="19" y2="12"/>
          </svg>
          Create QR Code
        </router-link>
      </header>

      <div class="qrcodes-grid" v-if="qrcodesStore.qrcodes.length">
        <div
          v-for="qr in qrcodesStore.qrcodes"
          :key="qr.id"
          class="qr-card"
        >
          <div class="qr-preview" :style="{ background: qr.style?.backgroundColor || '#ffffff' }">
            <img
              v-if="previews[qr.id]"
              :src="previews[qr.id]"
              alt="QR Preview"
              class="qr-image"
            />
            <div v-else class="qr-placeholder">
              <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                <rect x="3" y="3" width="6" height="6"/>
                <rect x="15" y="3" width="6" height="6"/>
                <rect x="3" y="15" width="6" height="6"/>
                <rect x="15" y="15" width="6" height="6"/>
              </svg>
            </div>
          </div>
          <div class="qr-info">
            <h3 class="qr-title">{{ qr.name }}</h3>
            <p class="qr-link">{{ getLinkSlug(qr.linkId) }}</p>
          </div>
          <div class="qr-actions">
            <router-link :to="`/qrcodes/${qr.id}`" class="action-btn" title="Edit">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
              </svg>
            </router-link>
            <button @click="downloadQR(qr, 'png')" class="action-btn" title="Download PNG">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                <polyline points="7 10 12 15 17 10"/>
                <line x1="12" y1="15" x2="12" y2="3"/>
              </svg>
            </button>
            <button @click="confirmDelete(qr)" class="action-btn delete" title="Delete">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polyline points="3 6 5 6 21 6"/>
                <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
              </svg>
            </button>
          </div>
        </div>
      </div>

      <div v-else class="empty-state">
        <div class="empty-icon">
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
            <rect x="3" y="3" width="6" height="6"/>
            <rect x="15" y="3" width="6" height="6"/>
            <rect x="3" y="15" width="6" height="6"/>
            <rect x="15" y="15" width="6" height="6"/>
            <rect x="9" y="9" width="6" height="6"/>
          </svg>
        </div>
        <h2>No QR codes yet</h2>
        <p>Create your first QR code design</p>
        <router-link to="/qrcodes/new" class="cta">Create QR Code</router-link>
      </div>

      <!-- Delete Confirmation Modal -->
      <div v-if="showDeleteModal" class="modal-overlay" @click.self="showDeleteModal = false">
        <div class="modal modal-sm">
          <h2>Delete QR Code?</h2>
          <p>Are you sure you want to delete this QR code design?</p>
          <div class="modal-actions">
            <button @click="showDeleteModal = false" class="ghost">Cancel</button>
            <button @click="deleteQR" class="cta danger">Delete</button>
          </div>
        </div>
      </div>
    </div>
  </AppLayout>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import AppLayout from '../../components/layout/AppLayout.vue';
import { useWorkspaceStore } from '../../stores/workspace.js';
import { useQRCodesStore } from '../../stores/qrcodes.js';
import { useLinksStore } from '../../stores/links.js';
import { qrcodesApi } from '../../api/qrcodes.js';

const workspaceStore = useWorkspaceStore();
const qrcodesStore = useQRCodesStore();
const linksStore = useLinksStore();

const previews = ref({});
const showDeleteModal = ref(false);
const deletingQR = ref(null);

const fetchPreviews = async () => {
  for (const qr of qrcodesStore.qrcodes) {
    try {
      const preview = await qrcodesStore.getQRCodePreview(qr.id);
      previews.value[qr.id] = preview.dataUrl;
    } catch (err) {
      console.error('Failed to fetch preview:', err);
    }
  }
};

const getLinkSlug = (linkId) => {
  const link = linksStore.links.find(l => l.id === linkId);
  return link ? `/${link.slug}` : 'No link';
};

const downloadQR = async (qr, format) => {
  const url = qrcodesStore.getQRCodeExportUrl(qr.id, format, 512);
  const link = document.createElement('a');
  link.href = url;
  link.download = `${qr.name}.${format}`;
  link.click();
};

const confirmDelete = (qr) => {
  deletingQR.value = qr;
  showDeleteModal.value = true;
};

const deleteQR = async () => {
  if (deletingQR.value) {
    await qrcodesStore.deleteQRCode(deletingQR.value.id);
    delete previews.value[deletingQR.value.id];
    showDeleteModal.value = false;
    deletingQR.value = null;
  }
};

onMounted(async () => {
  await qrcodesStore.fetchQRCodes();
  await linksStore.fetchLinks();
  await fetchPreviews();
});

watch(() => workspaceStore.currentWorkspaceId, async () => {
  if (workspaceStore.currentWorkspaceId) {
    previews.value = {};
    await qrcodesStore.fetchQRCodes();
    await linksStore.fetchLinks();
    await fetchPreviews();
  }
});
</script>

<style scoped>
.qrcodes-page {
  max-width: 1200px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 32px;
}

.page-header h1 {
  font-size: 1.75rem;
  margin-bottom: 4px;
}

.subtitle {
  color: var(--muted);
}

.cta {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.qrcodes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
}

.qr-card {
  background: var(--surface);
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.qr-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.qr-preview {
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 32px;
}

.qr-image {
  max-width: 100%;
  max-height: 100%;
  border-radius: 8px;
}

.qr-placeholder {
  color: var(--muted);
}

.qr-info {
  padding: 16px 20px;
}

.qr-title {
  font-size: 1.1rem;
  margin-bottom: 4px;
}

.qr-link {
  color: var(--muted);
  font-size: 0.9rem;
}

.qr-actions {
  display: flex;
  gap: 8px;
  padding: 0 20px 20px;
}

.action-btn {
  flex: 1;
  height: 40px;
  border: none;
  border-radius: 10px;
  background: var(--bg);
  color: var(--muted);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.15s ease;
}

.action-btn:hover {
  background: var(--line);
  color: var(--ink);
}

.action-btn.delete:hover {
  background: #fef2f2;
  color: #dc2626;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: var(--surface);
  border-radius: 20px;
}

.empty-icon {
  color: var(--muted);
  margin-bottom: 16px;
}

.empty-state h2 {
  margin-bottom: 8px;
}

.empty-state p {
  color: var(--muted);
  margin-bottom: 24px;
}

/* Modal styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal {
  background: var(--surface);
  border-radius: 24px;
  padding: 32px;
  width: 100%;
  max-width: 400px;
}

.modal-sm {
  text-align: center;
}

.modal-sm h2 {
  margin-bottom: 12px;
}

.modal-sm p {
  color: var(--muted);
  margin-bottom: 24px;
}

.modal-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
}

.cta.danger {
  background: #dc2626;
}
</style>
