<template>
   <Head title="Start" />
  <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">{{ props.galleryHeading }}</h1>
        <div class="absolute top-4 right-4">
          <button @click="toggleTheme" class="theme-toggle-button">
            {{ currentTheme === 'light' ? __('api.dark_mode') : __('api.light_mode') }}
        </button>
        </div>
        <GalleryGrid :images="paginatedImages" @imageTapped="showContextMenu" :translations="props.translations" />
        <Navigation 
          :currentPage="currentPage" 
          :totalPages="totalPages" 
          @prevPage="prevPage" 
          @nextPage="nextPage" 
        />
      </div>
    </div>

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

    <StyleSelector
      v-if="currentOverlayComponent === 'styleSelector'"
      :image_id="selectedImage.id"
      @styleSelected="applyStyle"
      @back="goBackToContextMenu"
      @close="currentOverlayComponent = null; selectedImage = 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" :progress="processingProgress" />
    <PrintQuantityModal
      v-if="currentOverlayComponent === 'printQuantityModal'"
      @close="currentOverlayComponent = null"
      @printConfirmed="handlePrintConfirmed"
      :maxCopies="maxCopiesSetting"
    />
      </div>
</template>

<script setup>
import { defineProps } from 'vue';

const props = defineProps({
  galleryHeading: String,
  translations: Object,
});

const images = ref([]);
let fetchInterval = null;

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.');
    });
};
import { Head } from '@inertiajs/vue3'; 
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 PrintQuantityModal from '../Components/PrintQuantityModal.vue'; // Import the new component
import axios from 'axios';
import { ref, computed, onMounted, onUnmounted } from 'vue';

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 processingProgress = ref(0); // To store the progress percentage
const errorMessage = ref(null); // New ref for error messages
const isLoading = ref(false); // New ref for loading state
const currentTheme = ref('light'); // New ref for current theme
const maxCopiesSetting = ref(10); // Default to 10, will be fetched from backend

let touchStartX = 0;
let touchEndX = 0;

const applyTheme = (theme) => {
  document.documentElement.classList.remove('light', 'dark');
  document.documentElement.classList.add(theme);
  localStorage.setItem('theme', theme);
  currentTheme.value = theme;
};

const toggleTheme = () => {
  const newTheme = currentTheme.value === 'light' ? 'dark' : 'light';
  applyTheme(newTheme);
};

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 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('Showing print quantity modal for image:', selectedImage.value);
  currentOverlayComponent.value = 'printQuantityModal';
};

const handlePrintConfirmed = (quantity) => {
  console.log(`Printing ${quantity} copies of image:`, selectedImage.value);
  currentOverlayComponent.value = null; // Close the modal

  axios.post('/api/print-image', {
    image_id: selectedImage.value.id,
    image_path: selectedImage.value.path,
    quantity: quantity,
  })
  .then(response => {
    console.log('Print request sent successfully:', response.data);
    showError('Print request sent successfully!');
  })
  .catch(error => {
    console.error('Error sending print request:', error);
    showError(error.response?.data?.error || 'Failed to send print request.');
  });
};

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
  processingProgress.value = 0; // Reset progress

  // Send style change request to backend first
  axios.post('/api/images/style-change', {
    image_id: imageId,
    style_id: style.id,
  })
  .then(response => {
    console.log('Style change request sent:', response.data);
    // Store the prompt_id and plugin from the backend response
    const promptId = response.data.prompt_id;
    const plugin = response.data.plugin;

    // Handle different plugins differently
    if (plugin === 'ComfyUi') {
      // For ComfyUI, use WebSocket for progress monitoring
      axios.get(`/api/comfyui-url?style_id=${style.id}`)
        .then(comfyResponse => {
          const comfyUiBaseUrl = comfyResponse.data.comfyui_url;
          const wsUrl = `ws://${new URL(comfyUiBaseUrl).host}/ws`;
          const ws = new WebSocket(wsUrl);

          ws.onopen = () => {
            console.log('WebSocket connected to ComfyUI.');

            ws.onmessage = (event) => {
              const message = JSON.parse(event.data);
              if (message.type === 'progress') {
                console.log('ComfyUI Progress Message:', message);
                const { value, max } = message.data;
                const progress = (max > 0) ? (value / max) * 100 : 0;
                if (message.data.prompt_id === promptId) {
                  processingProgress.value = progress;

                  if (processingProgress.value >= 100) {
                    console.log('Frontend: Progress reached 100%. Attempting to fetch final image.', { promptId: promptId });
                    // Fetch the final styled image from the backend
                    axios.get(`/api/images/fetch-styled/${promptId}`)
                      .then(imageResponse => {
                        console.log('Frontend: Successfully fetched styled image.', imageResponse.data);
                        styledImage.value = imageResponse.data.styled_image;
                        currentOverlayComponent.value = 'styledImageDisplay';
                        fetchImages(); // Refresh gallery
                      })
                      .catch(imageError => {
                        console.error('Frontend: Error fetching styled image:', imageError.response?.data?.error || imageError.message);
                        showError(imageError.response?.data?.error || 'Failed to fetch styled image.');
                      })
                      .finally(() => {
                        console.log('Frontend: Final fetch process completed.');
                        isLoading.value = false;
                        processingProgress.value = 0;
                        ws.close();
                      });
                  }
                }
              } else {
                console.warn('Received unexpected WebSocket message type:', message.type, message);
              }
            };
          };

          ws.onerror = (error) => {
            console.error('WebSocket error:', error);
            showError('WebSocket connection error.');
            isLoading.value = false;
            processingProgress.value = 0;
          };

          ws.onclose = () => {
            console.log('WebSocket closed.');
          };
        })
        .catch(error => {
          console.error('Error fetching ComfyUI URL:', error);
          showError(error.response?.data?.error || 'Failed to get ComfyUI URL.');
          isLoading.value = false;
        });
    } else {
      // For other plugins, use polling approach
      const pollForStyledImage = () => {
        axios.get(`/api/images/fetch-styled/${promptId}`)
          .then(imageResponse => {
            console.log('Frontend: Successfully fetched styled image.', imageResponse.data);
            styledImage.value = imageResponse.data.styled_image;
            currentOverlayComponent.value = 'styledImageDisplay';
            fetchImages(); // Refresh gallery
            isLoading.value = false;
            processingProgress.value = 0;
          })
          .catch(imageError => {
            console.error('Frontend: Error fetching styled image:', imageError.response?.data?.error || imageError.message);
            // If the image is not ready yet, continue polling
            if (imageError.response?.status === 404) {
              // Update progress if available
              if (imageError.response?.data?.progress !== undefined) {
                processingProgress.value = imageError.response.data.progress;
              }
              // Continue polling
              setTimeout(pollForStyledImage, 2000); // Poll every 2 seconds
            } else {
              showError(imageError.response?.data?.error || 'Failed to fetch styled image.');
              isLoading.value = false;
              processingProgress.value = 0;
            }
          });
      };
      
      // Start polling for the styled image
      pollForStyledImage();
    }
  })
  .catch(error => {
    console.error('Error applying style:', error);
    showError(error.response?.data?.error || 'Failed to apply style.');
    isLoading.value = false;
    processingProgress.value = 0;
  });
};

const keepStyledImage = (imageToKeep) => {
  console.log('Keeping styled image:', imageToKeep);
  // Implement API call to mark image as kept/permanent if needed
  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(() => {
  // Apply theme from localStorage on mount
  const savedTheme = localStorage.getItem('theme');
  if (savedTheme) {
    applyTheme(savedTheme);
  } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
    applyTheme('dark');
  } else {
    applyTheme('light');
  }

  fetchImages();

  // Fetch image refresh interval from API
  axios.get('/api/image-refresh-interval')
    .then(response => {
      const interval = response.data.interval * 1000;
      fetchInterval = setInterval(fetchImages, interval);
    })
    .catch(error => {
      console.error('Error fetching image refresh interval:', error);
      fetchInterval = setInterval(fetchImages, 5000); // Fallback to 5 seconds
    });

  // Fetch max number of copies setting from API
  axios.get('/api/max-copies-setting')
    .then(response => {
      maxCopiesSetting.value = response.data.max_copies;
    })
    .catch(error => {
      console.error('Error fetching max copies setting:', error);
    });
});

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;
}

.theme-toggle-button {
  margin-top: 10px;
  padding: 8px 15px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 0.9em;
}

.theme-toggle-button:hover {
  background-color: #0056b3;
}

.image-visibility-toggle-button {
  margin-top: 10px;
  padding: 8px 15px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 0.9em;
  margin-left: 10px;
}

.image-visibility-toggle-button:hover {
  background-color: #218838;
}
</style>