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

const router = useRouter()
const uploadedPhotos = ref<string[]>([])
const fileInputRef = ref<HTMLInputElement>()

const totalPhotos = 4

const cropImageTo34 = (imageSrc: string): Promise<string> => {
  return new Promise((resolve) => {
    const img = new Image()
    img.onload = () => {
      const canvas = document.createElement('canvas')
      const context = canvas.getContext('2d')

      if (!context) {
        resolve(imageSrc)
        return
      }

      const imgWidth = img.width
      const imgHeight = img.height

      // คำนวณขนาดสำหรับ 3:4 aspect ratio
      const targetAspectRatio = 3/4 // width:height = 3:4
      let cropWidth, cropHeight, cropX, cropY

      if (imgWidth / imgHeight > targetAspectRatio) {
        // ภาพกว้างกว่าที่ต้องการ - ครอบด้านข้าง
        cropHeight = imgHeight
        cropWidth = imgHeight * targetAspectRatio
        cropX = (imgWidth - cropWidth) / 2
        cropY = 0
      } else {
        // ภาพสูงกว่าที่ต้องการ - ครอบด้านบน/ล่าง
        cropWidth = imgWidth
        cropHeight = imgWidth / targetAspectRatio
        cropX = 0
        cropY = (imgHeight - cropHeight) / 2
      }

      // ตั้งค่าขนาด canvas เป็น 3:4 (720x960)
      const finalWidth = 720
      const finalHeight = 960

      canvas.width = finalWidth
      canvas.height = finalHeight

      // วาดภาพที่ครอบแล้วไปยัง canvas
      context.drawImage(
        img,
        cropX, cropY, cropWidth, cropHeight, // ตำแหน่งและขนาดที่ครอบจากภาพต้นฉบับ
        0, 0, finalWidth, finalHeight // ตำแหน่งและขนาดใน canvas
      )

      // แปลงเป็น base64
      const croppedDataUrl = canvas.toDataURL('image/jpeg', 0.9)
      resolve(croppedDataUrl)
    }
    img.src = imageSrc
  })
}

const triggerFileInput = () => {
  fileInputRef.value?.click()
}

const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = target.files

  if (!files) return

  // แปลงไฟล์เป็น base64 และครอบเป็น 3:4
  for (const file of Array.from(files)) {
    if (uploadedPhotos.value.length >= totalPhotos) break

    const reader = new FileReader()
    reader.onload = async (e) => {
      const result = e.target?.result as string
      if (result) {
        // ครอบภาพให้เป็น 3:4 ก่อนเก็บ
        const croppedImage = await cropImageTo34(result)
        uploadedPhotos.value.push(croppedImage)
      }
    }
    reader.readAsDataURL(file)
  }

  // เคลียร์ input
  target.value = ''
}

const removePhoto = (index: number) => {
  uploadedPhotos.value.splice(index, 1)
}

const proceedToNext = () => {
  if (uploadedPhotos.value.length !== totalPhotos) {
    alert(`กรุณาอัพโหลดภาพให้ครบ ${totalPhotos} รูป`)
    return
  }

  // เก็บรูปภาพไว้ใน localStorage
  localStorage.setItem('photobooth-photos', JSON.stringify(uploadedPhotos.value))
  router.push('/printstep')
}

const goBack = () => {
  router.push('/selectsource')
}
</script>

<template>
  <div class="upload-container">
    <header class="header">
      <button @click="goBack" class="back-button">← กลับ</button>
      <h1>อัพโหลดภาพ</h1>
      <span class="photo-counter">{{ uploadedPhotos.length }}/{{ totalPhotos }}</span>
    </header>

    <section class="upload-section">
      <div class="upload-area" @click="triggerFileInput">
        <div class="upload-icon">📁</div>
        <h3>คลิกเพื่อเลือกภาพ</h3>
        <p>หรือลากและวางไฟล์ภาพลงที่นี่</p>
        <p class="file-types">รองรับ: JPG, PNG, GIF</p>
      </div>

      <input
        ref="fileInputRef"
        type="file"
        accept="image/*"
        multiple
        @change="handleFileSelect"
        class="hidden-input"
      />
    </section>

    <section class="preview-section" v-if="uploadedPhotos.length > 0">
      <h3>ภาพที่เลือก</h3>
      <div class="photo-grid">
        <div
          v-for="(photo, index) in uploadedPhotos"
          :key="index"
          class="photo-item"
        >
          <img :src="photo" :alt="`Uploaded photo ${index + 1}`" />
          <button @click="removePhoto(index)" class="remove-button">✕</button>
          <span class="photo-number">{{ index + 1 }}</span>
        </div>

        <!-- Placeholder สำหรับรูปที่ยังไม่ได้เลือก -->
        <div
          v-for="i in totalPhotos - uploadedPhotos.length"
          :key="`placeholder-${i}`"
          class="photo-placeholder"
          @click="triggerFileInput"
        >
          <div class="placeholder-icon">+</div>
        </div>
      </div>
    </section>

    <section class="action-section" v-if="uploadedPhotos.length === totalPhotos">
      <button @click="proceedToNext" class="next-button">
        ถัดไป
      </button>
    </section>
  </div>
</template>

<style scoped>
.upload-container {
  min-height: 100vh;
  padding: 2rem;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 2rem;
}

.back-button {
  background: #6c757d;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
}

.header h1 {
  margin: 0;
  color: #333;
  font-size: 2rem;
}

.photo-counter {
  background: #007bff;
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 20px;
  font-weight: bold;
}

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

.upload-area {
  background: white;
  border: 2px dashed #dee2e6;
  border-radius: 16px;
  padding: 3rem 2rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-area:hover {
  border-color: #007bff;
  background: #f8f9ff;
}

.upload-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
  color: #6c757d;
}

.upload-area h3 {
  margin: 0 0 0.5rem 0;
  color: #333;
  font-size: 1.5rem;
}

.upload-area p {
  margin: 0.5rem 0;
  color: #666;
}

.file-types {
  font-size: 0.9rem;
  color: #999;
}

.hidden-input {
  display: none;
}

.preview-section {
  flex: 1;
}

.preview-section h3 {
  margin-bottom: 1rem;
  color: #333;
  text-align: center;
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 1rem;
  margin-bottom: 2rem;
}

.photo-item, .photo-placeholder {
  position: relative;
  aspect-ratio: 3/4;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
}

.photo-item:hover {
  transform: scale(1.02);
}

.photo-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-button {
  position: absolute;
  top: 8px;
  right: 8px;
  background: rgba(220, 53, 69, 0.9);
  color: white;
  border: none;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.8rem;
  transition: all 0.3s ease;
}

.remove-button:hover {
  background: rgba(220, 53, 69, 1);
  transform: scale(1.1);
}

.photo-number {
  position: absolute;
  bottom: 8px;
  left: 8px;
  background: rgba(0,0,0,0.7);
  color: white;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.8rem;
  font-weight: bold;
}

.photo-placeholder {
  background: #f8f9fa;
  border: 2px dashed #dee2e6;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.photo-placeholder:hover {
  border-color: #007bff;
  background: #f8f9ff;
}

.placeholder-icon {
  font-size: 2rem;
  color: #6c757d;
}

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

.next-button {
  background: #28a745;
  color: white;
  border: none;
  padding: 1rem 2rem;
  font-size: 1.2rem;
  font-weight: bold;
  border-radius: 50px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(40,167,69,0.3);
}

.next-button:hover {
  background: #218838;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(40,167,69,0.4);
}

@media (max-width: 768px) {
  .photo-grid {
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  }
}
</style>