<template>
  <AppLayout>
    <div class="designer-page">
      <header class="page-header">
        <div>
          <router-link to="/qrcodes" class="back-link">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M19 12H5"/>
              <path d="M12 19l-7-7 7-7"/>
            </svg>
            Back to QR Codes
          </router-link>
          <h1>{{ isEditing ? 'Edit QR Code' : 'Create QR Code' }}</h1>
        </div>
        <div class="header-actions">
          <button @click="downloadQR('svg')" class="ghost" :disabled="!previewUrl">
            <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>
            SVG
          </button>
          <button @click="downloadQR('png')" class="ghost" :disabled="!previewUrl">
            <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>
            PNG
          </button>
          <button @click="save" class="cta" :disabled="saving || !formData.name || !formData.linkId">
            {{ saving ? 'Saving...' : 'Save' }}
          </button>
        </div>
      </header>

      <div class="designer-grid">
        <section class="preview-section">
          <div class="preview-card" :style="{ background: formData.style.backgroundColor }">
            <img
              v-if="previewUrl"
              :src="previewUrl"
              alt="QR Preview"
              class="preview-image"
            />
            <div v-else class="preview-placeholder">
              <svg width="64" height="64" 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>
              <p>Select a link to preview</p>
            </div>
          </div>
        </section>

        <section class="settings-section">
          <div class="settings-card">
            <h2>Basic Info</h2>

            <div class="form-group">
              <label for="name">Name *</label>
              <input
                id="name"
                v-model="formData.name"
                type="text"
                placeholder="My QR Code"
                required
              />
            </div>

            <div class="form-group">
              <label for="linkId">Link *</label>
              <select id="linkId" v-model="formData.linkId" required>
                <option value="">Select a link</option>
                <option v-for="link in linksStore.links" :key="link.id" :value="link.id">
                  {{ link.title || link.slug }} ({{ link.slug }})
                </option>
              </select>
            </div>
          </div>

          <div class="settings-card">
            <h2>Style</h2>

            <div class="form-row">
              <div class="form-group">
                <label for="foregroundColor">Foreground</label>
                <div class="color-input">
                  <input
                    id="foregroundColor"
                    v-model="formData.style.foregroundColor"
                    type="color"
                  />
                  <input
                    v-model="formData.style.foregroundColor"
                    type="text"
                    class="color-text"
                  />
                </div>
              </div>

              <div class="form-group">
                <label for="backgroundColor">Background</label>
                <div class="color-input">
                  <input
                    id="backgroundColor"
                    v-model="formData.style.backgroundColor"
                    type="color"
                  />
                  <input
                    v-model="formData.style.backgroundColor"
                    type="text"
                    class="color-text"
                  />
                </div>
              </div>
            </div>

            <div class="form-group">
              <label for="errorCorrection">Error Correction</label>
              <select id="errorCorrection" v-model="formData.style.errorCorrectionLevel">
                <option value="L">Low (7%)</option>
                <option value="M">Medium (15%)</option>
                <option value="Q">Quartile (25%)</option>
                <option value="H">High (30%)</option>
              </select>
              <p class="hint">Higher correction allows for more damage tolerance but increases QR size</p>
            </div>

            <div class="form-group">
              <label for="quietZone">Quiet Zone</label>
              <input
                id="quietZone"
                v-model.number="formData.style.quietZone"
                type="range"
                min="1"
                max="6"
              />
              <span class="range-value">{{ formData.style.quietZone }} modules</span>
            </div>

            <div class="form-group">
              <label>Module Shape</label>
              <div class="shape-selector">
                <button
                  v-for="shape in moduleShapes"
                  :key="shape.value"
                  :class="{ active: formData.style.moduleShape === shape.value }"
                  @click="formData.style.moduleShape = shape.value"
                  class="shape-btn"
                >
                  <span class="shape-icon" :class="shape.value.toLowerCase()"></span>
                  {{ shape.label }}
                </button>
              </div>
            </div>

            <div class="form-group">
              <label>Eye Shape</label>
              <div class="shape-selector">
                <button
                  v-for="shape in eyeShapes"
                  :key="shape.value"
                  :class="{ active: formData.style.eyeShape === shape.value }"
                  @click="formData.style.eyeShape = shape.value"
                  class="shape-btn"
                >
                  <span class="shape-icon" :class="shape.value.toLowerCase()"></span>
                  {{ shape.label }}
                </button>
              </div>
              <p class="hint">Eyes are the large corner patterns for scanner detection</p>
            </div>
          </div>

          <div class="settings-card">
            <h2>Logo</h2>
            <div class="logo-section">
              <div class="current-logo" v-if="formData.logoAssetId">
                <img :src="getLogoUrl(formData.logoAssetId)" alt="Current logo" class="logo-preview" />
                <button @click="removeLogo" class="remove-logo-btn" title="Remove logo">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="18" y1="6" x2="6" y2="18"/>
                    <line x1="6" y1="6" x2="18" y2="18"/>
                  </svg>
                </button>
              </div>
              <div class="logo-upload" v-else>
                <label class="upload-btn">
                  <input
                    type="file"
                    @change="handleLogoUpload"
                    accept="image/png,image/jpeg,image/svg+xml"
                    hidden
                  />
                  <svg width="20" height="20" 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="17 8 12 3 7 8"/>
                    <line x1="12" y1="3" x2="12" y2="15"/>
                  </svg>
                  Upload Logo
                </label>
              </div>
              <div v-if="assets.length > 0 && !formData.logoAssetId" class="existing-logos">
                <p class="hint">Or select from existing:</p>
                <div class="logos-grid">
                  <button
                    v-for="asset in assets"
                    :key="asset.id"
                    @click="selectLogo(asset)"
                    class="logo-option"
                  >
                    <img :src="asset.url" :alt="asset.filename" />
                  </button>
                </div>
              </div>
              <p class="hint" v-if="formData.logoAssetId">Use high error correction (H) for better logo visibility</p>
            </div>
          </div>

          <div class="settings-card">
            <h2>Presets</h2>
            <div class="presets-grid">
              <button
                v-for="preset in presets"
                :key="preset.name"
                @click="applyPreset(preset)"
                class="preset-btn"
                :style="{
                  background: preset.style.backgroundColor,
                  color: preset.style.foregroundColor,
                  borderColor: preset.style.foregroundColor
                }"
              >
                {{ preset.name }}
              </button>
            </div>
          </div>
        </section>
      </div>

      <div v-if="error" class="error-toast">
        {{ error }}
      </div>
    </div>
  </AppLayout>
</template>

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

const route = useRoute();
const router = useRouter();
const workspaceStore = useWorkspaceStore();
const linksStore = useLinksStore();
const assetsStore = useAssetsStore();
const qrcodesStore = useQRCodesStore();

const isEditing = computed(() => !!route.params.id);
const saving = ref(false);
const error = ref('');
const previewUrl = ref('');
const previewTimeout = ref(null);
const uploadingLogo = ref(false);
const assets = computed(() => assetsStore.assets.filter(a => a.type === 'Logo'));

const formData = ref({
  name: '',
  linkId: '',
  logoAssetId: null,
  style: {
    foregroundColor: '#000000',
    backgroundColor: '#ffffff',
    errorCorrectionLevel: 'M',
    quietZone: 4,
    moduleShape: 'Square',
    eyeShape: 'Square',
  },
});

const moduleShapes = [
  { value: 'Square', label: 'Square' },
  { value: 'Rounded', label: 'Rounded' },
  { value: 'Dots', label: 'Dots' },
];

const eyeShapes = [
  { value: 'Square', label: 'Square' },
  { value: 'Rounded', label: 'Rounded' },
  { value: 'Circle', label: 'Circle' },
];

const getLogoUrl = (assetId) => {
  const asset = assetsStore.assets.find(a => a.id === assetId);
  return asset?.url || '';
};

const handleLogoUpload = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  uploadingLogo.value = true;
  try {
    const asset = await assetsStore.uploadAsset(file);
    formData.value.logoAssetId = asset.id;
    // If adding a logo, suggest high error correction
    if (formData.value.style.errorCorrectionLevel !== 'H') {
      formData.value.style.errorCorrectionLevel = 'H';
    }
  } catch (err) {
    error.value = 'Failed to upload logo: ' + err.message;
  } finally {
    uploadingLogo.value = false;
    event.target.value = '';
  }
};

const selectLogo = (asset) => {
  formData.value.logoAssetId = asset.id;
  // If adding a logo, suggest high error correction
  if (formData.value.style.errorCorrectionLevel !== 'H') {
    formData.value.style.errorCorrectionLevel = 'H';
  }
};

const removeLogo = () => {
  formData.value.logoAssetId = null;
};

const presets = [
  {
    name: 'Classic',
    style: { foregroundColor: '#000000', backgroundColor: '#ffffff', errorCorrectionLevel: 'M', quietZone: 4, moduleShape: 'Square', eyeShape: 'Square' }
  },
  {
    name: 'Modern',
    style: { foregroundColor: '#1a1a1a', backgroundColor: '#ffffff', errorCorrectionLevel: 'M', quietZone: 4, moduleShape: 'Rounded', eyeShape: 'Rounded' }
  },
  {
    name: 'Dots',
    style: { foregroundColor: '#000000', backgroundColor: '#ffffff', errorCorrectionLevel: 'H', quietZone: 4, moduleShape: 'Dots', eyeShape: 'Circle' }
  },
  {
    name: 'Ocean',
    style: { foregroundColor: '#0369a1', backgroundColor: '#e0f2fe', errorCorrectionLevel: 'M', quietZone: 4, moduleShape: 'Rounded', eyeShape: 'Rounded' }
  },
  {
    name: 'Forest',
    style: { foregroundColor: '#166534', backgroundColor: '#dcfce7', errorCorrectionLevel: 'M', quietZone: 4, moduleShape: 'Square', eyeShape: 'Square' }
  },
  {
    name: 'Purple',
    style: { foregroundColor: '#7c3aed', backgroundColor: '#f3e8ff', errorCorrectionLevel: 'M', quietZone: 4, moduleShape: 'Dots', eyeShape: 'Circle' }
  },
];

const applyPreset = (preset) => {
  formData.value.style = { ...preset.style };
};

const fetchPreview = async () => {
  if (!formData.value.linkId || !workspaceStore.currentWorkspaceId) {
    previewUrl.value = '';
    return;
  }

  // For new QR codes, we need to create a temporary one to get preview
  // For now, we'll just show a placeholder until saved
  if (isEditing.value) {
    try {
      const preview = await qrcodesStore.getQRCodePreview(route.params.id);
      previewUrl.value = preview.dataUrl;
    } catch (err) {
      console.error('Preview error:', err);
    }
  }
};

const save = async () => {
  if (!formData.value.name || !formData.value.linkId) return;

  saving.value = true;
  error.value = '';

  try {
    const data = {
      name: formData.value.name,
      shortLinkId: formData.value.linkId,
      logoAssetId: formData.value.logoAssetId,
      style: formData.value.style,
    };

    if (isEditing.value) {
      // For updates, handle logo removal
      if (!formData.value.logoAssetId) {
        data.removeLogo = true;
      }
      await qrcodesStore.updateQRCode(route.params.id, data);
    } else {
      await qrcodesStore.createQRCode(data);
    }

    router.push('/qrcodes');
  } catch (err) {
    error.value = err.message;
  } finally {
    saving.value = false;
  }
};

const downloadQR = async (format) => {
  if (!isEditing.value) return;

  const url = qrcodesStore.getQRCodeExportUrl(route.params.id, format, 512);
  const link = document.createElement('a');
  link.href = url;
  link.download = `${formData.value.name}.${format}`;
  link.click();
};

const loadExisting = async () => {
  if (!isEditing.value) return;

  try {
    const qr = await qrcodesApi.get(workspaceStore.currentWorkspaceId, route.params.id);
    const defaultStyle = {
      foregroundColor: '#000000',
      backgroundColor: '#ffffff',
      errorCorrectionLevel: 'M',
      quietZone: 4,
      moduleShape: 'Square',
      eyeShape: 'Square',
    };
    formData.value = {
      name: qr.name,
      linkId: qr.shortLinkId || qr.linkId,
      logoAssetId: qr.logoAssetId || null,
      style: { ...defaultStyle, ...qr.style },
    };
    await fetchPreview();
  } catch (err) {
    error.value = 'Failed to load QR code';
  }
};

watch(() => formData.value.style, () => {
  if (previewTimeout.value) clearTimeout(previewTimeout.value);
  previewTimeout.value = setTimeout(fetchPreview, 500);
}, { deep: true });

watch(() => formData.value.logoAssetId, () => {
  if (previewTimeout.value) clearTimeout(previewTimeout.value);
  previewTimeout.value = setTimeout(fetchPreview, 500);
});

onMounted(async () => {
  await Promise.all([
    linksStore.fetchLinks(),
    assetsStore.fetchAssets(),
  ]);
  if (isEditing.value) {
    await loadExisting();
  }
});
</script>

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

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

.back-link {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  color: var(--muted);
  font-size: 0.9rem;
  margin-bottom: 12px;
}

.page-header h1 {
  font-size: 1.75rem;
}

.header-actions {
  display: flex;
  gap: 12px;
}

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

.designer-grid {
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 32px;
}

.preview-section {
  position: sticky;
  top: 32px;
}

.preview-card {
  aspect-ratio: 1;
  max-width: 500px;
  border-radius: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.1);
  padding: 48px;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  border-radius: 12px;
}

.preview-placeholder {
  text-align: center;
  color: var(--muted);
}

.preview-placeholder p {
  margin-top: 16px;
}

.settings-section {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.settings-card {
  background: var(--surface);
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.settings-card h2 {
  font-size: 1.1rem;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group:last-child {
  margin-bottom: 0;
}

.form-group label {
  display: block;
  font-weight: 500;
  font-size: 0.9rem;
  margin-bottom: 8px;
}

.form-group input[type="text"],
.form-group select {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid var(--line);
  border-radius: 12px;
  font-size: 1rem;
  font-family: inherit;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: var(--accent);
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.color-input {
  display: flex;
  gap: 8px;
}

.color-input input[type="color"] {
  width: 48px;
  height: 48px;
  padding: 0;
  border: 1px solid var(--line);
  border-radius: 12px;
  cursor: pointer;
}

.color-input .color-text {
  flex: 1;
  padding: 12px;
  border: 1px solid var(--line);
  border-radius: 12px;
  font-family: monospace;
}

.form-group input[type="range"] {
  width: 100%;
  margin-bottom: 8px;
}

.range-value {
  font-size: 0.85rem;
  color: var(--muted);
}

.hint {
  font-size: 0.85rem;
  color: var(--muted);
  margin-top: 8px;
}

.presets-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}

.preset-btn {
  padding: 16px 12px;
  border: 2px solid;
  border-radius: 12px;
  font-weight: 600;
  font-size: 0.85rem;
  cursor: pointer;
  transition: transform 0.15s ease;
}

.preset-btn:hover {
  transform: scale(1.05);
}

.error-toast {
  position: fixed;
  bottom: 24px;
  left: 50%;
  transform: translateX(-50%);
  background: #dc2626;
  color: white;
  padding: 12px 24px;
  border-radius: 12px;
  font-weight: 500;
}

.logo-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.current-logo {
  position: relative;
  display: inline-block;
  width: 80px;
  height: 80px;
}

.logo-preview {
  width: 80px;
  height: 80px;
  object-fit: contain;
  border-radius: 12px;
  border: 1px solid var(--line);
  background: var(--bg);
}

.remove-logo-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #dc2626;
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-logo-btn:hover {
  background: #b91c1c;
}

.logo-upload {
  display: flex;
  gap: 12px;
}

.upload-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background: var(--bg);
  border: 2px dashed var(--line);
  border-radius: 12px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.15s ease;
}

.upload-btn:hover {
  border-color: var(--accent);
  color: var(--accent);
}

.existing-logos {
  margin-top: 8px;
}

.logos-grid {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 8px;
}

.logo-option {
  width: 48px;
  height: 48px;
  padding: 4px;
  border: 2px solid var(--line);
  border-radius: 8px;
  background: var(--surface);
  cursor: pointer;
  transition: all 0.15s ease;
}

.logo-option:hover {
  border-color: var(--accent);
}

.logo-option img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.shape-selector {
  display: flex;
  gap: 8px;
}

.shape-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 12px 8px;
  border: 2px solid var(--line);
  border-radius: 12px;
  background: var(--surface);
  cursor: pointer;
  transition: all 0.15s ease;
}

.shape-btn:hover {
  border-color: var(--muted);
}

.shape-btn.active {
  border-color: var(--accent);
  background: rgba(255, 106, 61, 0.1);
}

.shape-icon {
  width: 24px;
  height: 24px;
  background: var(--ink);
}

.shape-icon.square {
  border-radius: 2px;
}

.shape-icon.rounded {
  border-radius: 6px;
}

.shape-icon.dots,
.shape-icon.circle {
  border-radius: 50%;
}

@media (max-width: 900px) {
  .designer-grid {
    grid-template-columns: 1fr;
  }

  .preview-section {
    position: static;
  }

  .preview-card {
    max-width: 100%;
  }
}
</style>
