<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const photos = ref<string[]>([])
const layout = ref<'1x4' | '2x2'>('1x4')
const frame = ref<number>(0)
const cachedImageUrl = ref('')
const isGeneratingImage = ref(false)
const hasError = ref(false)

const qrCodeUrl = computed(() => {
  const filename = localStorage.getItem('photobooth-uploaded-filename')
  if (filename) {
    return `https://api.dekthai-online.com/apu-school/qrcode/photobooth.php?key=${filename}`
  }
  return ''
})
const downloadPageUrl = computed(() => {
  const filename = localStorage.getItem('photobooth-uploaded-filename')
  if (filename) {
    return `${window.location.origin}/download?image=${filename}`
  }
  return ''
})
onMounted(() => {
  // โหลดข้อมูลจาก localStorage
  const savedPhotos = localStorage.getItem('photobooth-photos')
  const savedLayout = localStorage.getItem('photobooth-layout')
  const savedFrame = localStorage.getItem('photobooth-frame')

  if (savedPhotos) {
    photos.value = JSON.parse(savedPhotos)
  }

  if (savedLayout) {
    layout.value = savedLayout as '1x4' | '2x2'
  }

  if (savedFrame) {
    frame.value = parseInt(savedFrame)
  }

  // สร้าง PNG และบันทึกใน localStorage (ถ้ายังไม่มี)
  generateAndCacheImage()
})

const getGridStyle = computed(() => {
  if (layout.value === '1x4') {
    return {
      display: 'grid',
      gridTemplateColumns: '1fr',
      gridTemplateRows: 'repeat(4, 1fr)',
      gap: '8px',
      aspectRatio: '1/1' // ทำให้แต่ละภาพยาวขึ้น (1:2 aspect ratio รวม)
    }
  } else {
    return {
      display: 'grid',
      gridTemplateColumns: 'repeat(2, 1fr)',
      gridTemplateRows: 'repeat(2, 1fr)',
      gap: '8px',
      aspectRatio: '1/1' // 2x2 เป็น square
    }
  }
})

const generateAndCacheImage = async () => {
  try {
    hasError.value = false
    if (photos.value.length === 0) return

    isGeneratingImage.value = true

    // สร้าง key สำหรับ localStorage
    const storageKey = `photobooth-${layout.value}-${frame.value}-${photos.value.length}`

    // ตรวจสอบว่ามี PNG ที่สร้างไว้แล้วหรือไม่
    const cachedImage = localStorage.getItem(storageKey)
    if (cachedImage) {
      cachedImageUrl.value = cachedImage
      await nextTick()
      return // มีแล้ว ไม่ต้องสร้างใหม่
    }

    // สร้าง canvas สำหรับรวมรูป
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')

    if (!context) {
      throw new Error('Could not get canvas context')
    }

  // ขนาดรูปแต่ละภาพ (360x480 = 3:4) - ลดขนาดลงเพื่อป้องกันปัญหา canvas ใหญ่เกินไป
  const photoWidth = 360
  const photoHeight = 480
  const gap = 20 // ระยะห่างระหว่างรูป

  let canvasWidth, canvasHeight
  let headerHeight = 0, footerHeight = 0
  let sidePadding = 0

  if (layout.value === '1x4') {
    // 1x4: 1 คอลัมน์ 4 แถว + header/footer
    headerHeight = 50
    footerHeight = 50
    sidePadding = 30 // padding ซ้ายขวาเพื่อให้ total width = 420
    canvasWidth = 420
    canvasHeight = headerHeight + (photoHeight * 4) + (gap * 3) + footerHeight
  } else {
    // 2x2: 2 คอลัมน์ 2 แถว + header/footer
    headerHeight = 60
    footerHeight = 60
    sidePadding = 20 // padding ซ้ายขวาเพื่อให้ total width = 780
    canvasWidth = 780
    canvasHeight = headerHeight + (photoHeight * 2) + gap + footerHeight
  }

  console.log('Canvas dimensions:', canvasWidth, 'x', canvasHeight)
  canvas.width = canvasWidth
  canvas.height = canvasHeight

  // วาด background ตาม frame
  drawFrameBackground(context, canvasWidth, canvasHeight, frame.value)

  // วาด header image
  const headerImagePath = layout.value === '1x4' ? '/assets/header-1x4.png' : '/assets/header-2x2.png'
  await drawHeaderFooterImage(context, headerImagePath, 0, 0, canvasWidth, headerHeight)

  // วาด footer image
  const footerImagePath = layout.value === '1x4' ? '/assets/footer-1x4.png' : '/assets/footer-2x2.png'
  await drawHeaderFooterImage(context, footerImagePath, 0, canvasHeight - footerHeight, canvasWidth, footerHeight)

  // วาดรูปภาพ (มี padding ซ้ายขวา)
  for (let i = 0; i < photos.value.length; i++) {
    const photoSrc = photos.value[i]
    if (!photoSrc) continue

    const img = new Image()
    img.src = photoSrc

    await new Promise((resolve) => {
      img.onload = () => {
        let x, y

        if (layout.value === '1x4') {
          // 1x4 layout - วาดรูปตรงกลาง (มี padding ซ้ายขวา)
          x = sidePadding
          y = headerHeight + i * (photoHeight + gap)
        } else {
          // 2x2 layout - วาดรูปตรงกลาง (มี padding ซ้ายขวา)
          const col = i % 2
          const row = Math.floor(i / 2)
          x = sidePadding + col * (photoWidth + gap)
          y = headerHeight + row * (photoHeight + gap)
        }

        // วาดรูปภาพ
        context.drawImage(img, x, y, photoWidth, photoHeight)
        resolve(void 0)
      }
      img.onerror = () => {
        console.error(`Failed to load image ${i}`)
        resolve(void 0)
      }
    })
  }

  // สร้าง PNG data URL และบันทึกใน localStorage
  const dataUrl = canvas.toDataURL('image/png')

  try {
    localStorage.setItem(storageKey, dataUrl)
    cachedImageUrl.value = dataUrl
    // ให้ Vue reactive update ก่อน
    await nextTick()
  } catch (error) {
    if (error instanceof DOMException && error.name === 'QuotaExceededError') {
      console.error('localStorage quota exceeded for cached image')
      alert('ไม่สามารถบันทึกภาพได้เนื่องจากพื้นที่เก็บข้อมูลไม่เพียงพอ')
    } else {
      console.error('Error saving cached image:', error)
      throw error
    }
  }
  } catch (error) {
    console.error('Error in generateAndCacheImage:', error)
    hasError.value = true
  } finally {
    isGeneratingImage.value = false
  }
}

const downloadImage = async () => {
  if (photos.value.length === 0) return

  // ตรวจสอบว่า cachedImageUrl มีหรือไม่ ถ้าไม่มีให้สร้างก่อน
  if (!cachedImageUrl.value) {
    await generateAndCacheImage()
  }

  // Download จาก cachedImageUrl
  downloadFromDataUrl(cachedImageUrl.value, `photobooth-${Date.now()}.png`)
}

const downloadFromDataUrl = (dataUrl: string, filename: string) => {
  const a = document.createElement('a')
  a.href = dataUrl
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

const drawFrameBackground = (context: CanvasRenderingContext2D, width: number, height: number, frameType: number) => {
  // วาด background ตาม frame type
  switch (frameType) {
    case 0: // Classic - white
      context.fillStyle = '#000000'
      break
    case 1: // Modern - gradient
      const gradient1 = context.createLinearGradient(0, 0, width, height)
      gradient1.addColorStop(0, '#667eea')
      gradient1.addColorStop(1, '#764ba2')
      context.fillStyle = gradient1
      break
    case 2: // Vintage - gradient
      const gradient2 = context.createLinearGradient(0, 0, width, height)
      gradient2.addColorStop(0, '#f093fb')
      gradient2.addColorStop(1, '#f5576c')
      context.fillStyle = gradient2
      break
    case 3: // Colorful - gradient
      const gradient3 = context.createLinearGradient(0, 0, width, height)
      gradient3.addColorStop(0, '#4facfe')
      gradient3.addColorStop(1, '#00f2fe')
      context.fillStyle = gradient3
      break
    case 4: // Minimal - light gray
      context.fillStyle = '#f8f9fa'
      break
    default:
      context.fillStyle = '#000000'
  }

  context.fillRect(0, 0, width, height)
}

const drawHeaderFooterImage = async (context: CanvasRenderingContext2D, imagePath: string, x: number, y: number, width: number, height: number) => {
  return new Promise<void>((resolve) => {
    const img = new Image()
    img.onload = () => {
      context.drawImage(img, x, y, width, height)
      resolve()
    }
    img.onerror = () => {
      console.warn(`Failed to load header/footer image: ${imagePath}, drawing placeholder`)
      // วาด placeholder color แทน
      if (imagePath.includes('header-1x4')) {
        context.fillStyle = '#007bff' // น้ำเงินสำหรับ 1x4 header
      } else if (imagePath.includes('footer-1x4')) {
        context.fillStyle = '#dc3545' // แดงสำหรับ 1x4 footer
      } else if (imagePath.includes('header-2x2')) {
        context.fillStyle = '#28a745' // เขียวสำหรับ 2x2 header
      } else if (imagePath.includes('footer-2x2')) {
        context.fillStyle = '#ffc107' // เหลืองสำหรับ 2x2 footer
      }
      context.fillRect(x, y, width, height)
      resolve()
    }
    img.src = imagePath
  })
}

const startOver = () => {
  // เคลียร์ข้อมูลและกลับไปหน้าแรก
  localStorage.removeItem('photobooth-photos')
  localStorage.removeItem('photobooth-layout')
  localStorage.removeItem('photobooth-frame')
  router.push('/')
}
</script>

<template>
  <div class="pickup-container">
    <header class="header">
      <h1>รูปถ่ายเสร็จแล้ว!</h1>
      <p>ดาวน์โหลดหรือแชร์รูปถ่ายของคุณ</p>
    </header>

    <section class="actions-section">
      <div class="action-buttons">
        <button @click="downloadImage" class="download-button">
          <span class="button-icon">📥</span>
          ดาวน์โหลด
        </button>

        <button @click="startOver" class="start-over-button">
        เริ่มใหม่
      </button>
      
      </div>
      
      <!-- QR Code สำหรับ download รูปถ่าย -->
      <div v-if="qrCodeUrl" class="qr-code-section">
        <h3>สแกน QR Code เพื่อดาวน์โหลด</h3>
        <a :href="downloadPageUrl" target="_blank" class="qr-code-link">
          <img :src="qrCodeUrl" alt="QR Code for downloading photo" class="qr-code-image" />
        </a>
        <p class="qr-hint">หรือ <a :href="downloadPageUrl" target="_blank" class="download-link">คลิกที่นี่</a> เพื่อเปิดในแท็บใหม่</p>
      </div>

    </section>

    <section class="result-section">
      <div class="photo-result">
        <div class="photo-frame"> <!-- Removed dynamic class for frame, styling applied directly -->
          <div v-if="isGeneratingImage && !cachedImageUrl" class="loading-indicator">
            <div class="spinner"></div>
            <p>กำลังสร้างภาพ...</p>
          </div>

          <img v-else-if="cachedImageUrl" :src="cachedImageUrl" alt="Combined Photo" class="combined-image" />

          <div v-else-if="hasError" class="error-message">
            <p>ไม่สามารถสร้างภาพได้</p>
          </div>
        </div>
      </div>
    </section>



    <!-- <section class="footer-section">
      
    </section> -->
  </div>
</template>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Crete+Round&family=Old+Standard+TT&display=swap');

.pickup-container {
  min-height: 100vh;
  padding: 1.5rem; /* Adjusted padding */
  background: #fdfaf6; /* Light vintage paper color */
  color: #3e2723; /* Dark brown for text */
  font-family: 'Old Standard TT', serif;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.header {
  text-align: center;
  margin-bottom: 2.5rem; /* Adjusted margin */
}

.header h1 {
  font-size: 2.5rem;
  color: #5d4037; /* Darker brown for title */
  margin-bottom: 0.5rem;
  font-family: 'Crete Round', serif;
  text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
}

.header p {
  color: #6d4c41; /* Muted brown for paragraph */
  font-size: 1.1rem;
}

.result-section {
  margin-bottom: 2.5rem; /* Adjusted margin */
}

.photo-result {
  display: flex;
  justify-content: center;
}

.photo-frame {
  background: #e0d8cf; /* Lighter vintage tone for frame background */
  padding: 15px; /* Reduced padding for a tighter frame */
  border-radius: 8px; /* Softer border-radius */
  box-shadow: 0 5px 20px rgba(0,0,0,0.15); /* Softer shadow */
  max-width: 420px; /* Matched canvas width */
  width: 100%;
  border: 4px solid #a1887f; /* Vintage brown border */
}

/* Removed photo-grid and photo-cell, as combined-image takes over */

.combined-image {
  width: 100%;
  height: auto;
  border-radius: 4px; /* Slightly rounded corners for the photo itself */
  display: block;
  filter: sepia(0.1) brightness(0.95); /* Subtle sepia and brightness for vintage feel */
}

.loading-indicator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 2rem;
  color: #6d4c41; /* Muted brown */
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #bcaaa4; /* Muted gray/brown */
  border-top: 4px solid #8d6e63; /* Vintage brown spinner */
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-message {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem;
  color: #d32f2f; /* Darker red for error */
  text-align: center;
}

.actions-section {
  margin-bottom: 2rem;
}

.qr-code-section {
  margin-top: 2rem;
  text-align: center;
}

.qr-code-section h3 {
  color: #5d4037;
  font-size: 1.2rem;
  margin-bottom: 1rem;
  font-family: 'Crete Round', serif;
}

.qr-code-image {
  width: 150px;
  height: 150px;
  border: 2px solid #a1887f;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0,0,0,0.1);
  transition: transform 0.2s ease;
}

.qr-code-link:hover .qr-code-image {
  transform: scale(1.05);
}

.qr-hint {
  margin-top: 1rem;
  font-size: 0.9rem;
  color: #6d4c41;
}

.download-link {
  color: #8d6e63;
  text-decoration: underline;
  font-weight: bold;
}

.download-link:hover {
  color: #795548;
}

.action-buttons {
  display: flex;
  gap: 1.5rem; /* Increased gap */
  justify-content: center;
}

.download-button {
  background: #8d6e63; /* Vintage brown button */
  color: #fdfaf6;
  border: 2px solid #795548; /* Darker border */
  padding: 1rem 2.5rem; /* Larger padding */
  font-size: 1.2rem; /* Slightly larger font */
  font-weight: bold;
  border-radius: 20px; /* Softer border-radius */
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 0.75rem; /* Larger gap for icon */
  box-shadow: 0 4px 10px rgba(0,0,0,0.2);
  font-family: 'Crete Round', serif; /* Vintage font */
  text-transform: uppercase;
  letter-spacing: 1px;
}

.download-button:hover {
  background: #795548;
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(0,0,0,0.3);
}

.button-icon {
  font-size: 1.5rem; /* Larger icon */
}

.footer-section {
  margin-top: -20px;
}

.start-over-button {
  background: #6d4c41; /* Muted brown */
  color: #fdfaf6;
  border: 1px solid #5d4037;
  padding: 0.8rem 1.8rem; /* Adjusted padding */
  font-size: 1rem; /* Slightly smaller font */
  font-weight: bold;
  border-radius: 20px; /* Softer border-radius */
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  font-family: 'Old Standard TT', serif;
}

.start-over-button:hover {
  background: #5d4037;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
    align-items: center;
    gap: 1rem; /* Smaller gap on mobile */
  }

  .download-button, .start-over-button {
    width: 240px; /* Wider buttons on mobile */
    justify-content: center;
    font-size: 1.1rem;
    padding: 0.8rem 1.5rem;
  }

  .button-icon {
    font-size: 1.3rem;
  }

  .photo-frame {
    max-width: 90%; /* Adjust max-width for smaller screens */
    padding: 10px;
  }
  .header h1 {
    font-size: 2rem;
  }
}
</style>