<template>
  <div class="home">
    <div class="main-content">
      <div class="gallery-container" @touchstart="handleTouchStart" @touchend="handleTouchEnd">
        <h1 class="text-2xl font-bold text-center my-4">Style Gallery</h1>
        <GalleryGrid :images="paginatedImages" @imageTapped="showContextMenu" />
        <Navigation 
          :currentPage="currentPage" 
          :totalPages="totalPages" 
          @prevPage="prevPage" 
          @nextPage="nextPage" 
        />
      </div>
    </div>

    <ImageContextMenu 
      v-if="currentOverlayComponent === 'contextMenu'" 
      :position="contextMenuPosition" 
      :image="selectedImage" 
      @close="currentOverlayComponent = null" 
      @print="printImage" 
      @changeStyle="showStyleSelector" 
    />

    <StyleSelector 
      v-if="currentOverlayComponent === 'styleSelector'" 
      :position="contextMenuPosition" 
      :image_id="selectedImage.image_id"
      @styleSelected="applyStyle" 
      @back="goBackToContextMenu" 
      @close="currentOverlayComponent = null" 
    />

    <div v-if="errorMessage" class="fixed bottom-4 right-4 bg-red-500 text-white p-4 rounded-lg shadow-lg z-50">
      {{ errorMessage }}
    </div>
    <StyledImageDisplay
      v-if="currentOverlayComponent === 'styledImageDisplay'"
      :image="styledImage"
      @keep="keepStyledImage"
      @delete="deleteStyledImage"
    />

    <LoadingSpinner v-if="isLoading" />
      </div>
</template>

<script setup>
import Navigation from '../Components/Navigation.vue';
import GalleryGrid from '../Components/GalleryGrid.vue';
import ImageContextMenu from '../Components/ImageContextMenu.vue';
import StyleSelector from '../Components/StyleSelector.vue';
import StyledImageDisplay from '../Components/StyledImageDisplay.vue'; // Import the new component
import LoadingSpinner from '../Components/LoadingSpinner.vue'; // Import the new component
import axios from 'axios';
import { ref, computed, onMounted, onUnmounted } from 'vue';

const images = ref([]);
const imagesPerPage = 12;
const currentPage = ref(1);
const currentOverlayComponent = ref(null); // null, 'contextMenu', 'styleSelector', 'styledImageDisplay'
const contextMenuPosition = ref({ x: 0, y: 0 });
const selectedImage = ref(null);
const styledImage = ref(null); // To store the newly styled image
const errorMessage = ref(null); // New ref for error messages
const isLoading = ref(false); // New ref for loading state
let fetchInterval = null;
let touchStartX = 0;
let touchEndX = 0;


const totalPages = computed(() => {
  return Math.ceil(images.value.length / imagesPerPage);
});

const paginatedImages = computed(() => {
  const start = (currentPage.value - 1) * imagesPerPage;
  const end = start + imagesPerPage;
  return images.value.slice(start, end);
});

const fetchImages = () => {
  axios.get('/api/images')
    .then(response => {
      images.value = response.data;
    })
    .catch(error => {
      console.error('Error fetching images:', error);
      showError(error.response?.data?.error || 'An unknown error occurred.');
    });
};

const showError = (message) => {
  errorMessage.value = message;
  setTimeout(() => {
    errorMessage.value = null;
  }, 5000); // Clear error after 5 seconds
};

const showContextMenu = (image, event) => {
  selectedImage.value = image;
  contextMenuPosition.value = { x: event.clientX, y: event.clientY };
  currentOverlayComponent.value = 'contextMenu';
};

const printImage = () => {
  console.log('Printing image:', selectedImage.value);
  currentOverlayComponent.value = null;
};

const showStyleSelector = () => {
  currentOverlayComponent.value = 'styleSelector';
};

const goBackToContextMenu = () => {
  currentOverlayComponent.value = 'contextMenu';
};

const applyStyle = (style, imageId) => {
  console.log('Applying style:', style.title, 'to image:', imageId);
  currentOverlayComponent.value = null; // Close style selector immediately
  isLoading.value = true; // Show loading spinner

  axios.post('/api/images/style-change', {
    image_id: imageId,
    style_id: style.id,
  })
  .then(response => {
    console.log('Style change request successful:', response.data);
    styledImage.value = response.data.styled_image;
    currentOverlayComponent.value = 'styledImageDisplay';
  })
  .catch(error => {
    console.error('Error applying style:', error);
    showError(error.response?.data?.error || 'Failed to apply style.');
  })
  .finally(() => {
    isLoading.value = false; // Hide loading spinner
  });
};

const keepStyledImage = (imageToKeep) => {
  console.log('Keeping styled image:', imageToKeep);
  // Implement API call to mark image as kept/permanent if needed
  // For now, just refresh the image list to show the new image
  fetchImages();
  currentOverlayComponent.value = null; // Close the display
};

const deleteStyledImage = (imageToDelete) => {
  console.log('Deleting styled image:', imageToDelete);
  // Implement API call to delete the temporary styled image
  currentOverlayComponent.value = null; // Close the display
};

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  }
};

const handleTouchStart = (event) => {
  touchStartX = event.touches[0].clientX;
};

const handleTouchEnd = (event) => {
  touchEndX = event.changedTouches[0].clientX;
  handleSwipeGesture();
};

const handleSwipeGesture = () => {
  const swipeThreshold = 50; // Minimum distance for a swipe
  if (touchEndX < touchStartX - swipeThreshold) {
    // Swiped left
    nextPage();
  } else if (touchEndX > touchStartX + swipeThreshold) {
    // Swiped right
    prevPage();
  }
};

onMounted(() => {
  fetchImages();
  fetchInterval = setInterval(fetchImages, 5000);
});

onUnmounted(() => {
  clearInterval(fetchInterval);
});
</script>

<style scoped>
.home {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.main-content {
  display: flex;
  width: 100%;
  max-width: 1400px;
}

.gallery-container {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}
</style>