<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { __ } from '@wordpress/i18n'
import LoadingSpinner from '@/apps/settings/components/LoadingSpinner.vue'
import { getSavetoWishlistObj } from '@/config'
import { getI18n } from '@/helper'
import type { ImportSource, PreviewData, ImportStats } from '@/types'

const state = ref<'detecting' | 'no_sources' | 'select_source' | 'preview' | 'progress' | 'complete'>('detecting')
const sources = ref<ImportSource[]>([])
const selectedSource = ref<ImportSource | null>(null)
const previewData = ref<PreviewData | null>(null)
const importOptions = ref({
  merge_existing: false,
  preserve_default: true,
  preserve_privacy: true,
})
const isImporting = ref(false)
const importStats = ref<ImportStats>({})
const progressPercentage = ref(0)

const apiBase = getSavetoWishlistObj.rest_importer_url

// Check if there are wishlists to import
const hasWishlistsToImport = computed(() => {
  return previewData.value && 
  previewData.value.counts && 
  (previewData.value.counts.wishlists ?? 0) > 0
})

const sourceHasWishlists = computed(() => {
  return previewData.value &&
  previewData.value.counts &&
  (previewData.value.counts.countFromSource > 0)
})

onMounted(() => {
  detectSources()
})

const detectSources = async () => {
  state.value = 'detecting'
  try {
    const response = await fetch(`${apiBase}/sources`, {
      method: 'GET',
      headers: {
        'X-WP-Nonce': getSavetoWishlistObj.wpNonce,
      },
    })
    const data = await response.json()
    
    if (data.sources && data.sources.length > 0) {
      sources.value = data.sources
      state.value = 'select_source'
    } else {
      state.value = 'no_sources'
    }
  } catch (error) {
    state.value = 'no_sources'
  }
}

const selectSource = async (source: any) => {
  selectedSource.value = source
  state.value = 'preview'
  
  try {
    const response = await fetch(`${apiBase}/preview/${source.slug}`, {
      method: 'GET',
      headers: {
        'X-WP-Nonce': getSavetoWishlistObj.wpNonce,
      },
    })
    const data = await response.json()
    previewData.value = data
  } catch (error) {
    alert(getI18n('error_loading_preview', __('Error loading preview. Please try again.', 'saveto-wishlist-lite-for-woocommerce')))
  }
}

const startImport = async () => {
  if (!selectedSource.value) return
  
  isImporting.value = true
  state.value = 'progress'
  progressPercentage.value = 0
  
  try {
    const response = await fetch(`${apiBase}/import`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-WP-Nonce': getSavetoWishlistObj.wpNonce,
      },
      body: JSON.stringify({
        source: selectedSource.value.slug,
        options: importOptions.value,
      }),
    })
    
    const data = await response.json()
    
    if (data.success) {
      importStats.value = data.stats || {}
      progressPercentage.value = 100
      state.value = 'complete'
    } else {
      alert(getI18n('import_failed', __('Import failed:', 'saveto-wishlist-lite-for-woocommerce')) + ' ' + (data.message || getI18n('unknown_error', __('Unknown error', 'saveto-wishlist-lite-for-woocommerce'))))
      resetState()
    }
  } catch (error) {
    alert(getI18n('import_failed_try_again', __('Import failed. Please try again.', 'saveto-wishlist-lite-for-woocommerce')))
    resetState()
  } finally {
    isImporting.value = false
  }
}

const cancelImport = () => {
  if (confirm(getI18n('confirm_cancel_import', __('Are you sure you want to cancel the import?', 'saveto-wishlist-lite-for-woocommerce')))) {
    resetState()
  }
}

const resetState = () => {
  state.value = 'select_source'
  selectedSource.value = null
  previewData.value = null
  importStats.value = {}
  progressPercentage.value = 0
  isImporting.value = false
}
</script>

<template>
  <div class="stwlite-importer-tool">
    <!-- Source Detection State -->
    <div v-if="state === 'detecting'" class="stwlite-tw-p-6 stwlite-tw-text-center">
      <LoadingSpinner />
      <p class="stwlite-tw-mt-4 stwlite-tw-text-gray-600">
        {{ getI18n('detecting_sources', __('Detecting available import sources...', 'saveto-wishlist-lite-for-woocommerce')) }}
      </p>
    </div>

    <!-- No Sources State -->
    <div v-else-if="state === 'no_sources'" class="stwlite-tw-p-6 stwlite-tw-text-center">
      <div class="stwlite-tw-text-gray-400 stwlite-tw-mb-4">
        <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="stwlite-tw-mx-auto">
          <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
          <polyline points="7 10 12 15 17 10"/>
          <line x1="12" x2="12" y1="15" y2="3"/>
        </svg>
      </div>
      <h3 class="stwlite-tw-text-lg stwlite-tw-font-semibold stwlite-tw-text-gray-900 stwlite-tw-mb-2">
        {{ getI18n('no_import_sources', __('No Import Sources Detected', 'saveto-wishlist-lite-for-woocommerce')) }}
      </h3>
      <p class="stwlite-tw-text-gray-600">
        {{ getI18n('no_compatible_plugins', __('No compatible wishlist plugins were found. Install YITH WooCommerce Wishlist to import wishlists.', 'saveto-wishlist-lite-for-woocommerce')) }}
      </p>
    </div>

    <!-- Source Selection State -->
    <div v-else-if="state === 'select_source'" class="stwlite-tw-space-y-4">
      <h3 class="stwlite-tw-text-lg stwlite-tw-font-semibold stwlite-tw-text-gray-900 stwlite-tw-mb-4">
        {{ getI18n('select_import_source', __('Select Import Source', 'saveto-wishlist-lite-for-woocommerce')) }}
      </h3>
      <div class="stwlite-tw-grid stwlite-tw-grid-cols-1 md:stwlite-tw-grid-cols-2 stwlite-tw-gap-4">
        <div
          v-for="source in sources"
          :key="source.slug"
          @click="selectSource(source)"
          class="stwlite-tw-border stwlite-tw-border-gray-200 stwlite-tw-rounded-lg stwlite-tw-p-6 stwlite-tw-cursor-pointer stwlite-tw-transition-all stwlite-tw-border-solid hover:stwlite-tw-border-blue-500 hover:stwlite-tw-shadow-md"
        >
          <div class="stwlite-tw-flex stwlite-tw-items-start stwlite-tw-space-x-4">
            <div class="stwlite-tw-flex-1">
              <h4 class="stwlite-tw-font-semibold stwlite-tw-text-gray-900 stwlite-tw-mb-1 stwlite-tw-m-0 stwlite-tw-text-center">
                {{ source.name }}
              </h4>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Preview State -->
    <div v-else-if="state === 'preview'" class="stwlite-tw-space-y-6">
      <div class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-justify-between">
        <h3 class="stwlite-tw-text-lg stwlite-tw-font-semibold stwlite-tw-text-gray-900">
          {{ getI18n('import_preview', __('Import Preview', 'saveto-wishlist-lite-for-woocommerce')) }} - {{ selectedSource?.name }}
        </h3>
        <button
          @click="resetState"
          class="stwlite-tw-text-sm stwlite-tw-text-gray-600 hover:stwlite-tw-text-gray-900 stwlite-tw-border-solid stwlite-tw-border stwlite-tw-border-gray-200 stwlite-tw-rounded-lg stwlite-tw-p-2"
        >
          {{ getI18n('back', __('← Back', 'saveto-wishlist-lite-for-woocommerce')) }}
        </button>
      </div>

      <!-- Summary Card -->
      <div class="stwlite-tw-bg-white stwlite-tw-border stwlite-tw-border-gray-200 stwlite-tw-rounded-lg stwlite-tw-p-6">
        <h4 class="stwlite-tw-font-semibold stwlite-tw-text-gray-900 stwlite-tw-mb-4">
          {{ getI18n('data_summary', __('Data Summary', 'saveto-wishlist-lite-for-woocommerce')) }}
        </h4>
        
        <!-- Show message when no wishlists to import -->
        <div v-if="!hasWishlistsToImport" class="stwlite-tw-text-center stwlite-tw-py-8">
          <!-- Check icon when source has wishlists -->
          <div v-if="sourceHasWishlists" class="stwlite-tw-text-green-600 stwlite-tw-mb-3">
            <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="stwlite-tw-mx-auto">
              <path d="M20 6 9 17l-5-5"/>
            </svg>
          </div>
          <!-- Information icon when source has no wishlists -->
          <div v-else class="stwlite-tw-text-blue-600 stwlite-tw-mb-3">
            <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="stwlite-tw-mx-auto">
              <circle cx="12" cy="12" r="10"/>
              <line x1="12" y1="16" x2="12" y2="12"/>
              <line x1="12" y1="8" x2="12.01" y2="8"/>
            </svg>
          </div>
          <p v-if="sourceHasWishlists" class="stwlite-tw-text-lg stwlite-tw-font-semibold stwlite-tw-text-gray-900 stwlite-tw-mb-2">
            {{ getI18n('all_wishlists_imported', __('All wishlists have been imported!', 'saveto-wishlist-lite-for-woocommerce')) }}
          </p>
          <p v-else class="stwlite-tw-text-lg stwlite-tw-font-semibold stwlite-tw-text-gray-900 stwlite-tw-mb-2">
            {{ getI18n('no_wishlists_to_import', __('No wishlists to import from this source.', 'saveto-wishlist-lite-for-woocommerce')) }}
          </p>
          <p class="stwlite-tw-text-sm stwlite-tw-text-gray-600">
            {{ getI18n('no_new_wishlists', __('There are no new wishlists to import from this source.', 'saveto-wishlist-lite-for-woocommerce')) }}
          </p>
        </div>
        
        <!-- Show counts when wishlists available -->
        <div v-else class="stwlite-tw-grid stwlite-tw-grid-cols-2 md:stwlite-tw-grid-cols-4 stwlite-tw-gap-4">
          <div>
            <div class="stwlite-tw-text-2xl stwlite-tw-font-bold stwlite-tw-text-gray-900">
              {{ previewData?.counts.wishlists ?? 0 }}
            </div>
            <div class="stwlite-tw-text-sm stwlite-tw-text-gray-600">
              {{ getI18n('wishlists', __('Wishlists to Import', 'saveto-wishlist-lite-for-woocommerce')) }}
            </div>
          </div>
          <div>
            <div class="stwlite-tw-text-2xl stwlite-tw-font-bold stwlite-tw-text-gray-900">
              {{ previewData?.counts.items ?? 0 }}
            </div>
            <div class="stwlite-tw-text-sm stwlite-tw-text-gray-600">
              {{ getI18n('items', __('Items', 'saveto-wishlist-lite-for-woocommerce')) }}
            </div>
          </div>
          <div>
            <div class="stwlite-tw-text-2xl stwlite-tw-font-bold stwlite-tw-text-gray-900">
              {{ previewData?.counts.users ?? 0 }}
            </div>
            <div class="stwlite-tw-text-sm stwlite-tw-text-gray-600">
              {{ getI18n('users', __('Users', 'saveto-wishlist-lite-for-woocommerce')) }}
            </div>
          </div>
          <div v-if="previewData?.counts.guests && previewData?.counts.guests > 0">
            <div class="stwlite-tw-text-2xl stwlite-tw-font-bold stwlite-tw-text-yellow-600">
              {{ previewData?.counts.guests ?? 0 }}
            </div>
            <div class="stwlite-tw-text-sm stwlite-tw-text-gray-600">
              {{ getI18n('guest_lists_skipped', __('Guest Lists (will be skipped)', 'saveto-wishlist-lite-for-woocommerce')) }}
            </div>
          </div>
        </div>
      </div>

      <!-- Import Options -->
      <div v-if="hasWishlistsToImport" class="stwlite-tw-bg-white stwlite-tw-border stwlite-tw-border-gray-200 stwlite-tw-rounded-lg stwlite-tw-p-6">
        <h4 class="stwlite-tw-font-semibold stwlite-tw-text-gray-900 stwlite-tw-mb-4">
          {{ getI18n('import_options', __('Import Options', 'saveto-wishlist-lite-for-woocommerce')) }}
        </h4>
        <div class="stwlite-tw-space-y-4">
          <label class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-space-x-3">
            <input
              type="checkbox"
              v-model="importOptions.preserve_default"
              class="stwlite-tw-rounded stwlite-tw-border-gray-300 stwlite-tw-text-blue-600 focus:stwlite-tw-ring-blue-500"
            />
            <span class="stwlite-tw-text-sm stwlite-tw-text-gray-700">
              {{ getI18n('preserve_default_setting', __('Preserve default wishlist setting', 'saveto-wishlist-lite-for-woocommerce')) }}
            </span>
          </label>
          <label class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-space-x-3">
            <input
              type="checkbox"
              v-model="importOptions.preserve_privacy"
              class="stwlite-tw-rounded stwlite-tw-border-gray-300 stwlite-tw-text-blue-600 focus:stwlite-tw-ring-blue-500"
            />
            <span class="stwlite-tw-text-sm stwlite-tw-text-gray-700">
              {{ getI18n('preserve_privacy_settings', __('Preserve privacy settings', 'saveto-wishlist-lite-for-woocommerce')) }}
            </span>
          </label>
        </div>
      </div>

      <!-- Start Import Button -->
      <button
        v-if="hasWishlistsToImport"
        @click="startImport"
        :disabled="isImporting || !hasWishlistsToImport"
        class="stwlite-tw-w-full stwlite-tw-bg-blue-600 stwlite-tw-text-white stwlite-tw-py-3 stwlite-tw-px-6 stwlite-tw-rounded-lg stwlite-tw-font-semibold hover:stwlite-tw-bg-blue-700 disabled:stwlite-tw-opacity-50 disabled:stwlite-tw-cursor-not-allowed"
      >
        {{ isImporting ? getI18n('importing', __('Importing...', 'saveto-wishlist-lite-for-woocommerce')) : getI18n('start_import', __('Start Import', 'saveto-wishlist-lite-for-woocommerce')) }}
      </button>
    </div>

    <!-- Progress State -->
    <div v-else-if="state === 'progress'" class="stwlite-tw-space-y-6">
      <h3 class="stwlite-tw-text-lg stwlite-tw-font-semibold stwlite-tw-text-gray-900">
        {{ getI18n('importing', __('Importing...', 'saveto-wishlist-lite-for-woocommerce')) }}
      </h3>
      <div class="stwlite-tw-bg-white stwlite-tw-border stwlite-tw-border-gray-200 stwlite-tw-rounded-lg stwlite-tw-p-6">
        <div class="stwlite-tw-mb-4">
          <div class="stwlite-tw-flex stwlite-tw-justify-between stwlite-tw-text-sm stwlite-tw-text-gray-600 stwlite-tw-mb-2">
            <span>{{ getI18n('processing', __('Processing...', 'saveto-wishlist-lite-for-woocommerce')) }}</span>
            <span>{{ progressPercentage }}%</span>
          </div>
          <div class="stwlite-tw-w-full stwlite-tw-bg-gray-200 stwlite-tw-rounded-full stwlite-tw-h-2">
            <div
              class="stwlite-tw-bg-blue-600 stwlite-tw-h-2 stwlite-tw-rounded-full stwlite-tw-transition-all"
              :style="{ width: progressPercentage + '%' }"
            ></div>
          </div>
        </div>
        <button
          @click="cancelImport"
          class="stwlite-tw-text-sm stwlite-tw-text-red-600 hover:stwlite-tw-text-red-700"
        >
          {{ getI18n('cancel_import', __('Cancel Import', 'saveto-wishlist-lite-for-woocommerce')) }}
        </button>
      </div>
    </div>

    <!-- Complete State -->
    <div v-else-if="state === 'complete'" class="stwlite-tw-space-y-6">
      <div class="stwlite-tw-bg-green-50 stwlite-tw-border stwlite-tw-border-green-200 stwlite-tw-rounded-lg stwlite-tw-p-6">
        <div class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-space-x-3 stwlite-tw-mb-4">
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="stwlite-tw-text-green-600">
            <path d="M20 6 9 17l-5-5"/>
          </svg>
          <h3 class="stwlite-tw-text-lg stwlite-tw-font-semibold stwlite-tw-text-green-900">
            {{ getI18n('import_complete', __('Import Complete', 'saveto-wishlist-lite-for-woocommerce')) }}
          </h3>
        </div>

        <!-- Summary Statistics -->
        <div class="stwlite-tw-grid stwlite-tw-grid-cols-2 md:stwlite-tw-grid-cols-4 stwlite-tw-gap-4 stwlite-tw-mb-4">
          <div>
            <div class="stwlite-tw-text-2xl stwlite-tw-font-bold stwlite-tw-text-gray-900">
              {{ importStats.wishlists_imported ?? 0 }}
            </div>
            <div class="stwlite-tw-text-sm stwlite-tw-text-gray-600">
              {{ getI18n('wishlists_imported', __('Wishlists imported', 'saveto-wishlist-lite-for-woocommerce')) }}
            </div>
          </div>
          <div>
            <div class="stwlite-tw-text-2xl stwlite-tw-font-bold stwlite-tw-text-gray-900">
              {{ importStats.items_imported ?? 0 }}
            </div>
            <div class="stwlite-tw-text-sm stwlite-tw-text-gray-600">
              {{ getI18n('items_imported', __('Items imported', 'saveto-wishlist-lite-for-woocommerce')) }}
            </div>
          </div>
          <div>
            <div class="stwlite-tw-text-2xl stwlite-tw-font-bold stwlite-tw-text-gray-900">
              {{ importStats.users_affected ?? 0 }}
            </div>
            <div class="stwlite-tw-text-sm stwlite-tw-text-gray-600">
              {{ getI18n('users_affected', __('Users affected', 'saveto-wishlist-lite-for-woocommerce')) }}
            </div>
          </div>
          <div v-if="(importStats.wishlists_skipped ?? 0) > 0 || (importStats.items_skipped ?? 0) > 0">
            <div class="stwlite-tw-text-2xl stwlite-tw-font-bold stwlite-tw-text-yellow-600">
              {{ (importStats.wishlists_skipped ?? 0) + (importStats.items_skipped ?? 0) }}
            </div>
            <div class="stwlite-tw-text-sm stwlite-tw-text-gray-600">
              {{ getI18n('skipped', __('Skipped', 'saveto-wishlist-lite-for-woocommerce')) }}
            </div>
          </div>
        </div>

        <!-- Warnings -->
        <div v-if="(importStats.wishlists_skipped ?? 0) > 0 || (importStats.items_skipped ?? 0) > 0" class="stwlite-tw-mt-4 stwlite-tw-text-sm stwlite-tw-text-yellow-800">
          <p v-if="(importStats.wishlists_skipped ?? 0) > 0">
            • {{ importStats.wishlists_skipped }} {{ getI18n('wishlists_skipped_users', __('wishlists skipped', 'saveto-wishlist-lite-for-woocommerce')) }}
          </p>
          <p v-if="(importStats.items_skipped ?? 0) > 0">
            • {{ importStats.items_skipped }} {{ getI18n('items_skipped_products', __('items skipped (products deleted)', 'saveto-wishlist-lite-for-woocommerce')) }}
          </p>
        </div>

        <!-- Actions -->
        <div class="stwlite-tw-flex stwlite-tw-space-x-4 stwlite-tw-mt-6">
          <button
            @click="resetState"
            class="stwlite-tw-flex-1 stwlite-tw-bg-blue-600 stwlite-tw-text-white stwlite-tw-py-2 stwlite-tw-px-4 stwlite-tw-rounded-lg stwlite-tw-font-semibold hover:stwlite-tw-bg-blue-700"
          >
            {{ getI18n('import_another', __('Import Another', 'saveto-wishlist-lite-for-woocommerce')) }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.stwlite-importer-tool {
  @apply stwlite-tw-w-full;
}
</style>
