<template>
  <Modal :is-open="isOpen" @close="close" title="Share spritesheet" :initialWidth="500" :initialHeight="280">
    <div class="h-full flex flex-col">
      <div class="flex-1 overflow-auto p-4 space-y-4 dark:bg-gray-800">
        <!-- Loading state -->
        <div v-if="loading" class="flex flex-col items-center justify-center py-8">
          <i class="fas fa-circle-notch fa-spin text-3xl text-gray-400 dark:text-gray-500 mb-3"></i>
          <p class="text-sm text-gray-600 dark:text-gray-300">Uploading spritesheet...</p>
        </div>

        <!-- Success state -->
        <div v-else-if="shareUrl" class="space-y-4">
          <p class="text-sm text-gray-600 dark:text-gray-300">Your spritesheet is ready to share! Copy the link below:</p>

          <div class="flex items-center gap-2">
            <input type="text" :value="shareUrl" readonly class="flex-1 px-3 py-2 rounded-lg border border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100 text-sm font-mono" @focus="($event.target as HTMLInputElement).select()" />
            <button @click="copyToClipboard" class="px-4 py-2 rounded-lg bg-blue-500 hover:bg-blue-600 text-white text-sm font-medium transition-colors" :title="copied ? 'Copied!' : 'Copy to clipboard'">
              <i :class="copied ? 'fas fa-check' : 'fas fa-copy'"></i>
            </button>
          </div>

          <p v-if="copied" class="text-sm text-green-600 dark:text-green-400">Link copied to clipboard!</p>
        </div>

        <!-- Error state -->
        <div v-else-if="error" class="space-y-4">
          <p class="text-sm text-red-600 dark:text-red-400">{{ error }}</p>
          <button @click="retry" class="px-4 py-2 rounded-lg bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-100 text-sm font-medium transition-colors"><i class="fas fa-redo mr-2"></i>Try again</button>
        </div>

        <!-- Initial state (shouldn't normally be visible) -->
        <div v-else class="flex flex-col items-center justify-center py-8">
          <p class="text-sm text-gray-600 dark:text-gray-300">Preparing to share...</p>
        </div>
      </div>

      <div class="border-t border-gray-200 dark:border-gray-700 p-3 flex justify-end">
        <button type="button" class="px-4 py-2 rounded-lg bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-100" @click="close">Close</button>
      </div>
    </div>
  </Modal>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue';
  import Modal from './utilities/Modal.vue';

  const props = defineProps<{
    isOpen: boolean;
    shareFunction: () => Promise<{ id: string; url: string }>;
  }>();
  const emit = defineEmits<{ (e: 'close'): void }>();

  const loading = ref(false);
  const shareUrl = ref('');
  const error = ref('');
  const copied = ref(false);

  const close = () => emit('close');

  const performShare = async () => {
    loading.value = true;
    error.value = '';
    shareUrl.value = '';
    copied.value = false;

    try {
      const result = await props.shareFunction();
      shareUrl.value = result.url;
    } catch (e: any) {
      console.error('Failed to share spritesheet:', e);
      error.value = 'Failed to share spritesheet. Please try again later.';
    } finally {
      loading.value = false;
    }
  };

  const retry = () => {
    performShare();
  };

  const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(shareUrl.value);
      copied.value = true;
      setTimeout(() => {
        copied.value = false;
      }, 2000);
    } catch {
      // Fallback for older browsers
      const input = document.createElement('input');
      input.value = shareUrl.value;
      document.body.appendChild(input);
      input.select();
      document.execCommand('copy');
      document.body.removeChild(input);
      copied.value = true;
      setTimeout(() => {
        copied.value = false;
      }, 2000);
    }
  };

  // Start sharing when modal opens
  watch(
    () => props.isOpen,
    isOpen => {
      if (isOpen) {
        performShare();
      } else {
        // Reset state when closing
        loading.value = false;
        shareUrl.value = '';
        error.value = '';
        copied.value = false;
      }
    }
  );
</script>
