<script setup>
import { computed, onMounted, onUnmounted } from 'vue';

import { Image } from 'ant-design-vue';

import { XgVideoPlayer } from '#/components/video-player';
import { useMediaPreview } from '../composables/useMediaPreview.ts';
import { useThemeStore } from '../stores/theme.ts';

const themeStore = useThemeStore();
const { visible, mediaData, hidePreview, previewType } = useMediaPreview();

const showImagePreview = computed(
  () => visible.value && previewType.value === 'image',
);
const showVideoPreview = computed(
  () => visible.value && previewType.value === 'video',
);

const handleKeydown = (event) => {
  if (!visible.value) return;

  if (event.code === 'Escape') {
    hidePreview();
  }
};

onMounted(() => {
  document.addEventListener('keydown', handleKeydown);
});

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown);
});
</script>

<template>
  <Image
    :imgs="[{ src: mediaData }]"
    :visible="showImagePreview"
    @hide="hidePreview"
  />

  <div
    v-if="showVideoPreview"
    :class="{ dark: themeStore.isDarkMode }"
    class="media-preview-overlay"
    @click.self="hidePreview"
  >
    <div class="video-preview-container">
      <button class="preview-close-btn" @click="hidePreview">
        <i class="fas fa-times"></i>
      </button>

      <XgVideoPlayer
        :src="mediaData"
        class="preview-video"
        autoplay
      />
    </div>
  </div>
</template>

<style scoped>
.media-preview-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.9);
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  animation: fadeIn 0.3s ease;
}

.media-preview-overlay.dark {
  background: rgba(0, 0, 0, 0.95);
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.video-preview-container {
  position: relative;
  max-width: 90vw;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #000;
  border-radius: 12px;
  overflow: hidden;
}

.preview-close-btn {
  position: absolute;
  top: -50px;
  right: 0;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border: none;
  border-radius: 50%;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  transition: all 0.3s ease;
  z-index: 10;
}

.preview-close-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

.preview-video {
  width: 90vw;
  max-height: 85vh;
}

@media (max-width: 768px) {
  .video-preview-container {
    max-width: 95vw;
    max-height: 95vh;
  }

  .preview-close-btn {
    top: -40px;
    width: 36px;
    height: 36px;
    font-size: 16px;
  }

  .preview-video {
    width: 95vw;
    max-height: 90vh;
  }
}
</style>
