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

const router = useRouter()
const videoRef = ref<HTMLVideoElement>()
const canvasRef = ref<HTMLCanvasElement>()
const photos = ref<string[]>([])
const currentPhotoIndex = ref(0)
const isCapturing = ref(false)
const isAutoCapturing = ref(false)
const countdown = ref(0)
const stream = ref<MediaStream | null>(null)

const totalPhotos = 4

onMounted(async () => {
  await startCamera()
})

onUnmounted(() => {
  stopCamera()
})

const startCamera = async () => {
  try {
    const constraints = {
      video: {
        facingMode: 'user',
        width: { ideal: 720 },
        height: { ideal: 960 }
      }
    }

    stream.value = await navigator.mediaDevices.getUserMedia(constraints)
    if (videoRef.value) {
      videoRef.value.srcObject = stream.value
    }
  } catch (error) {
    console.error('Error accessing camera:', error)
    alert('ไม่สามารถเข้าถึงกล้องได้ กรุณาตรวจสอบสิทธิ์การใช้งานกล้อง')
  }
}

const stopCamera = () => {
  if (stream.value) {
    stream.value.getTracks().forEach(track => track.stop())
    stream.value = null
  }
}

const captureSinglePhoto = () => {
  if (!videoRef.value || !canvasRef.value || isCapturing.value) return

  isCapturing.value = true

  const video = videoRef.value
  const canvas = canvasRef.value
  const context = canvas.getContext('2d')

  if (!context) return

  const videoWidth = video.videoWidth
  const videoHeight = video.videoHeight

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

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

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

  canvas.width = finalWidth
  canvas.height = finalHeight

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

  // แปลงเป็น base64
  const photoDataUrl = canvas.toDataURL('image/jpeg', 0.9)
  photos.value.push(photoDataUrl)
  currentPhotoIndex.value++

  setTimeout(() => {
    isCapturing.value = false
  }, 200)
}

const startAutoCapture = () => {
  if (isAutoCapturing.value) return

  isAutoCapturing.value = true
  photos.value = []
  currentPhotoIndex.value = 0

  const captureNextPhoto = () => {
    if (currentPhotoIndex.value >= totalPhotos) {
      // ถ่ายครบแล้ว ไปหน้าถัดไป
      isAutoCapturing.value = false
      proceedToNext()
      return
    }

    // นับถอยหลังสำหรับรูปปัจจุบัน
    countdown.value = 3

    const countdownInterval = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(countdownInterval)
        countdown.value = 0

        // ถ่ายภาพ
        captureSinglePhoto()

        // ถ่ายรูปต่อไปหลังจาก delay สั้นๆ
        setTimeout(() => {
          captureNextPhoto()
        }, 500)
      }
    }, 1000)
  }

  // เริ่มถ่ายรูปแรก
  captureNextPhoto()
}

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

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

const retakePhoto = () => {
  photos.value = []
  currentPhotoIndex.value = 0
  isAutoCapturing.value = false
  countdown.value = 0
}
</script>

<template>
  <div class="shooting-container">
    <header class="header">
      <button @click="goBack" class="back-button">← กลับ</button>
      <h1>ถ่ายภาพ</h1>
      <span class="photo-counter">{{ currentPhotoIndex }}/{{ totalPhotos }}</span>
    </header>

    <section class="camera-section">
      <div class="camera-container">
        <video
          ref="videoRef"
          autoplay
          playsinline
          muted
          class="camera-video"
        ></video>
        <canvas ref="canvasRef" class="hidden-canvas"></canvas>

        <div class="camera-overlay">
          <div class="capture-guide">
            <div class="guide-frame"></div>
          </div>

          <!-- Countdown overlay -->
          <div v-if="countdown > 0" class="countdown-overlay">
            <div class="countdown-info">รูปที่ {{ currentPhotoIndex + 1 }}</div>
            <div class="countdown-number">{{ countdown }}</div>
          </div>
        </div>
      </div>

      <div class="controls">
        <button
          @click="startAutoCapture"
          :disabled="isAutoCapturing || currentPhotoIndex >= totalPhotos"
          class="capture-button"
          :class="{ capturing: isAutoCapturing }"
        >
          <span v-if="!isAutoCapturing && currentPhotoIndex === 0">📷 ถ่ายทั้ง 4 รูป</span>
          <span v-else-if="isAutoCapturing">กำลังถ่าย...</span>
          <span v-else>ถ่ายเสร็จแล้ว</span>
        </button>

        <button
          v-if="currentPhotoIndex > 0 && !isAutoCapturing"
          @click="retakePhoto"
          class="retake-button"
        >
          ถ่ายใหม่ทั้งหมด
        </button>
      </div>
    </section>

    <section class="preview-section" v-if="photos.length > 0">
      <h3>ภาพที่ถ่ายแล้ว</h3>
      <div class="photo-preview">
        <div
          v-for="(photo, index) in photos"
          :key="index"
          class="preview-item"
        >
          <img :src="photo" :alt="`Photo ${index + 1}`" />
          <span class="photo-number">{{ index + 1 }}</span>
        </div>
      </div>
    </section>
  </div>
</template>

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

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

.back-button {
  background: rgba(255,255,255,0.2);
  color: white;
  border: 1px solid rgba(255,255,255,0.3);
  padding: 0.5rem 1rem;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
}

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

.photo-counter {
  background: rgba(255,255,255,0.2);
  padding: 0.5rem 1rem;
  border-radius: 20px;
  font-weight: bold;
}

.camera-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2rem;
}

.camera-container {
  position: relative;
  width: 100%;
  max-width: 400px;
  aspect-ratio: 3/4;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0,0,0,0.3);
}

.camera-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.hidden-canvas {
  display: none;
}

.camera-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.countdown-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  animation: countdownFade 1s ease-in-out;
}

.countdown-info {
  font-size: 1.5rem;
  font-weight: bold;
  color: white;
  margin-bottom: 1rem;
  text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
}

.countdown-number {
  font-size: 8rem;
  font-weight: bold;
  color: white;
  text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
  animation: countdownPulse 1s ease-in-out;
}

.capture-guide {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.guide-frame {
  width: 80%;
  height: 80%;
  border: 3px solid rgba(255,255,255,0.5);
  border-radius: 12px;
}

.controls {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
}

.capture-button {
  background: #ff6b6b;
  color: white;
  border: none;
  padding: 1rem 2rem;
  font-size: 1.2rem;
  font-weight: bold;
  border-radius: 50px;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 200px;
}

.capture-button:hover:not(:disabled) {
  background: #ff5252;
  transform: scale(1.05);
}

.capture-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.capturing {
  animation: pulse 0.5s ease-in-out;
}

.retake-button {
  background: rgba(255,255,255,0.2);
  color: white;
  border: 1px solid rgba(255,255,255,0.3);
  padding: 0.75rem 1.5rem;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.retake-button:hover {
  background: rgba(255,255,255,0.3);
}

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

.preview-section h3 {
  margin-bottom: 1rem;
  color: #ccc;
}

.photo-preview {
  display: flex;
  gap: 1rem;
  justify-content: center;
  flex-wrap: wrap;
}

.preview-item {
  position: relative;
  width: 60px;
  aspect-ratio: 3/4;
  border-radius: 8px;
  overflow: hidden;
}

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

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

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

@keyframes countdownFade {
  0% { opacity: 0; }
  10% { opacity: 1; }
  90% { opacity: 1; }
  100% { opacity: 0; }
}

@keyframes countdownPulse {
  0% { transform: scale(0.8); opacity: 0; }
  20% { transform: scale(1.2); opacity: 1; }
  50% { transform: scale(1); }
  80% { transform: scale(1.1); }
  100% { transform: scale(1); opacity: 0; }
}

@media (max-width: 768px) {
  .camera-container {
    max-width: 100%;
  }

  .photo-preview {
    gap: 0.5rem;
  }

  .preview-item {
    width: 60px;
    height: 60px;
  }
}
</style>