<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useApi } from '@/composables/useApi'
import { useAuthStore } from '@/stores/auth'
import type { Module } from '@/types'
import { ShoppingCart, Package, Search, Filter, X, Check, Download, AlertCircle } from 'lucide-vue-next'
import { safeFixed } from '@/utils/formatters'

const api = useApi()
const auth = useAuthStore()

const isLoading = ref(false)
const modules = ref<Module[]>([])
const myModules = ref<Module[]>([])
const activeTab = ref<'catalog' | 'my-modules'>('catalog')
const searchQuery = ref('')
const selectedCategory = ref<string>('all')
const selectedModule = ref<Module | null>(null)
const showDetailModal = ref(false)
const showPurchaseModal = ref(false)
const isPurchasing = ref(false)
const purchaseError = ref('')

const categories = [
  { value: 'all', label: 'All Modules' },
  { value: 'loot', label: 'Loot' },
  { value: 'events', label: 'Events' },
  { value: 'economy', label: 'Economy' },
  { value: 'kits', label: 'Kits' },
  { value: 'admin', label: 'Admin Tools' },
  { value: 'pvp', label: 'PVP' },
  { value: 'pve', label: 'PVE' },
  { value: 'building', label: 'Building' },
]

const filteredModules = computed(() => {
  let result = activeTab.value === 'catalog' ? modules.value : myModules.value

  if (selectedCategory.value !== 'all') {
    result = result.filter(m => m.category === selectedCategory.value)
  }

  if (searchQuery.value.trim()) {
    const q = searchQuery.value.toLowerCase()
    result = result.filter(m =>
      m.name.toLowerCase().includes(q) ||
      m.description.toLowerCase().includes(q)
    )
  }

  return result
})

async function loadCatalog() {
  isLoading.value = true
  try {
    const data = await api.get<Module[]>('/modules/catalog')
    modules.value = data
  } catch (error) {
    console.error('Failed to load module catalog:', error)
  } finally {
    isLoading.value = false
  }
}

async function loadMyModules() {
  isLoading.value = true
  try {
    const data = await api.get<Module[]>('/modules/my-modules')
    myModules.value = data
  } catch (error) {
    console.error('Failed to load my modules:', error)
  } finally {
    isLoading.value = false
  }
}

async function initiatePurchase(module: Module) {
  selectedModule.value = module
  showPurchaseModal.value = true
  purchaseError.value = ''
}

async function confirmPurchase() {
  if (!selectedModule.value || !auth.license?.id) return

  isPurchasing.value = true
  purchaseError.value = ''

  try {
    const response = await api.post<{ payment_url?: string; success: boolean; message?: string }>('/modules/purchase', {
      module_id: selectedModule.value.id,
      license_id: auth.license.id
    })

    if (response.payment_url) {
      // Redirect to external payment provider
      window.location.href = response.payment_url
    } else if (response.success) {
      // Instant purchase confirmed
      showPurchaseModal.value = false
      selectedModule.value = null
      await loadCatalog()
      await loadMyModules()
    }
  } catch (error: any) {
    purchaseError.value = error.message || 'Purchase failed. Please try again.'
  } finally {
    isPurchasing.value = false
  }
}

async function installModule(module: Module) {
  try {
    await api.post('/modules/install', { module_id: module.id })
    await loadMyModules()
  } catch (error) {
    console.error('Failed to install module:', error)
  }
}

function openDetailModal(module: Module) {
  selectedModule.value = module
  showDetailModal.value = true
}

function closeModals() {
  showDetailModal.value = false
  showPurchaseModal.value = false
  selectedModule.value = null
  purchaseError.value = ''
}

function categoryBadgeClass(category: string): string {
  const colors: Record<string, string> = {
    loot: 'bg-yellow-500/15 text-yellow-400',
    events: 'bg-purple-500/15 text-purple-400',
    economy: 'bg-green-500/15 text-green-400',
    kits: 'bg-blue-500/15 text-blue-400',
    admin: 'bg-oxide-500/15 text-oxide-400',
    pvp: 'bg-red-500/15 text-red-400',
    pve: 'bg-indigo-500/15 text-indigo-400',
    building: 'bg-orange-500/15 text-orange-400',
  }
  return colors[category] || 'bg-neutral-700/50 text-neutral-400'
}

onMounted(() => {
  loadCatalog()
  loadMyModules()
})
</script>

<template>
  <div class="p-6 space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-3">
        <ShoppingCart class="w-5 h-5 text-oxide-500" />
        <div>
          <h1 class="text-2xl font-bold text-neutral-100">Module Store</h1>
          <p class="text-sm text-neutral-500 mt-0.5">
            Extend your server with premium gameplay modules
          </p>
        </div>
      </div>
      <div class="flex bg-neutral-800 rounded-lg border border-neutral-700 overflow-hidden">
        <button
          @click="activeTab = 'catalog'"
          class="px-4 py-2 text-sm font-medium transition-colors"
          :class="activeTab === 'catalog' ? 'bg-oxide-500/15 text-oxide-400' : 'text-neutral-400 hover:text-neutral-200'"
        >
          <span class="flex items-center gap-2">
            <Package class="w-4 h-4" />
            Catalog
          </span>
        </button>
        <button
          @click="activeTab = 'my-modules'"
          class="px-4 py-2 text-sm font-medium transition-colors"
          :class="activeTab === 'my-modules' ? 'bg-oxide-500/15 text-oxide-400' : 'text-neutral-400 hover:text-neutral-200'"
        >
          <span class="flex items-center gap-2">
            <Download class="w-4 h-4" />
            My Modules ({{ myModules.length }})
          </span>
        </button>
      </div>
    </div>

    <!-- Filters -->
    <div class="flex items-center gap-4">
      <div class="relative flex-1 max-w-md">
        <Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-neutral-500" />
        <input
          v-model="searchQuery"
          type="text"
          placeholder="Search modules..."
          class="w-full pl-10 pr-3 py-2 bg-neutral-800 border border-neutral-700 rounded-lg text-sm text-neutral-100 placeholder-neutral-500 focus:outline-none focus:ring-2 focus:ring-oxide-500/50 focus:border-oxide-500 transition-colors"
        />
      </div>
      <div class="flex items-center gap-2">
        <Filter class="w-4 h-4 text-neutral-500" />
        <select
          v-model="selectedCategory"
          class="px-3 py-2 bg-neutral-800 border border-neutral-700 rounded-lg text-sm text-neutral-100 focus:outline-none focus:ring-2 focus:ring-oxide-500/50 focus:border-oxide-500 transition-colors"
        >
          <option v-for="cat in categories" :key="cat.value" :value="cat.value">
            {{ cat.label }}
          </option>
        </select>
      </div>
    </div>

    <!-- Loading state -->
    <div v-if="isLoading" class="flex items-center justify-center py-12">
      <div class="text-neutral-500">Loading modules...</div>
    </div>

    <!-- Module grid -->
    <div v-else-if="filteredModules.length > 0" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
      <div
        v-for="module in filteredModules"
        :key="module.id"
        class="bg-neutral-900 border border-neutral-800 rounded-lg overflow-hidden hover:border-oxide-500/30 transition-all group"
      >
        <!-- Preview Image -->
        <div class="relative h-40 bg-neutral-800 overflow-hidden">
          <img
            v-if="module.preview_image_url"
            :src="module.preview_image_url"
            :alt="module.name"
            class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
          />
          <div v-else class="w-full h-full flex items-center justify-center">
            <Package class="w-12 h-12 text-neutral-700" />
          </div>
          <div class="absolute top-2 right-2">
            <span class="text-xs font-medium px-2 py-1 rounded-full" :class="categoryBadgeClass(module.category)">
              {{ module.category }}
            </span>
          </div>
          <div v-if="module.is_purchased" class="absolute top-2 left-2">
            <span class="text-xs font-medium px-2 py-1 rounded-full bg-green-500/20 text-green-400 flex items-center gap-1">
              <Check class="w-3 h-3" />
              Purchased
            </span>
          </div>
        </div>

        <!-- Content -->
        <div class="p-4 space-y-3">
          <div>
            <div class="flex items-start justify-between gap-2 mb-1">
              <h3 class="text-base font-semibold text-neutral-100">{{ module.name }}</h3>
              <span class="text-lg font-bold text-oxide-400 shrink-0">${{ safeFixed(module.price, 2) }}</span>
            </div>
            <p class="text-sm text-neutral-500 line-clamp-2">{{ module.description }}</p>
          </div>

          <!-- Features -->
          <div class="flex flex-wrap gap-1.5">
            <span
              v-for="(feature, idx) in module.features.slice(0, 3)"
              :key="idx"
              class="text-xs text-neutral-400 bg-neutral-800 px-2 py-0.5 rounded"
            >
              {{ feature }}
            </span>
            <span v-if="module.features.length > 3" class="text-xs text-neutral-500">
              +{{ module.features.length - 3 }} more
            </span>
          </div>

          <!-- Actions -->
          <div class="flex gap-2 pt-2">
            <button
              @click="openDetailModal(module)"
              class="flex-1 py-2 text-sm font-medium text-neutral-300 bg-neutral-800 hover:bg-neutral-700 border border-neutral-700 rounded-lg transition-colors"
            >
              Details
            </button>
            <button
              v-if="!module.is_purchased"
              @click="initiatePurchase(module)"
              class="flex-1 py-2 text-sm font-medium text-white bg-oxide-600 hover:bg-oxide-700 rounded-lg transition-colors"
            >
              Purchase
            </button>
            <button
              v-else-if="!module.is_installed"
              @click="installModule(module)"
              class="flex-1 flex items-center justify-center gap-1.5 py-2 text-sm font-medium text-green-400 bg-green-500/10 hover:bg-green-500/20 border border-green-500/20 rounded-lg transition-colors"
            >
              <Download class="w-3.5 h-3.5" />
              Install
            </button>
            <button
              v-else
              disabled
              class="flex-1 flex items-center justify-center gap-1.5 py-2 text-sm font-medium text-green-400 bg-green-500/10 border border-green-500/20 rounded-lg cursor-default"
            >
              <Check class="w-3.5 h-3.5" />
              Installed
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Empty state -->
    <div v-else class="bg-neutral-900 border border-neutral-800 rounded-lg p-12 text-center">
      <Package class="w-12 h-12 text-neutral-600 mx-auto mb-3" />
      <h3 class="text-lg font-medium text-neutral-300 mb-1">
        {{ activeTab === 'catalog' ? 'No modules found' : 'No purchased modules' }}
      </h3>
      <p class="text-sm text-neutral-500">
        {{ activeTab === 'catalog' ? 'Try adjusting your filters.' : 'Browse the catalog to purchase modules.' }}
      </p>
    </div>

    <!-- Detail Modal -->
    <div
      v-if="showDetailModal && selectedModule"
      class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
      @click.self="closeModals"
    >
      <div class="bg-neutral-900 border border-neutral-800 rounded-lg max-w-3xl w-full max-h-[90vh] overflow-y-auto">
        <!-- Modal Header -->
        <div class="sticky top-0 bg-neutral-900 border-b border-neutral-800 px-6 py-4 flex items-start justify-between">
          <div class="flex-1">
            <div class="flex items-center gap-3 mb-2">
              <h2 class="text-xl font-bold text-neutral-100">{{ selectedModule.name }}</h2>
              <span class="text-xs font-medium px-2 py-1 rounded-full" :class="categoryBadgeClass(selectedModule.category)">
                {{ selectedModule.category }}
              </span>
            </div>
            <p class="text-sm text-neutral-400">Version {{ selectedModule.version }}</p>
          </div>
          <button
            @click="closeModals"
            class="p-2 text-neutral-400 hover:text-neutral-200 rounded-lg transition-colors"
          >
            <X class="w-5 h-5" />
          </button>
        </div>

        <!-- Modal Body -->
        <div class="p-6 space-y-6">
          <!-- Screenshots -->
          <div v-if="selectedModule.screenshots.length > 0" class="space-y-3">
            <h3 class="text-sm font-medium text-neutral-300 uppercase tracking-wider">Screenshots</h3>
            <div class="grid grid-cols-2 gap-3">
              <img
                v-for="(screenshot, idx) in selectedModule.screenshots"
                :key="idx"
                :src="screenshot"
                :alt="`Screenshot ${idx + 1}`"
                class="w-full h-48 object-cover rounded-lg border border-neutral-800"
              />
            </div>
          </div>

          <!-- Description -->
          <div class="space-y-3">
            <h3 class="text-sm font-medium text-neutral-300 uppercase tracking-wider">Description</h3>
            <p class="text-sm text-neutral-400 leading-relaxed">{{ selectedModule.description }}</p>
          </div>

          <!-- Features -->
          <div class="space-y-3">
            <h3 class="text-sm font-medium text-neutral-300 uppercase tracking-wider">Features</h3>
            <ul class="space-y-2">
              <li
                v-for="(feature, idx) in selectedModule.features"
                :key="idx"
                class="flex items-start gap-2 text-sm text-neutral-400"
              >
                <Check class="w-4 h-4 text-oxide-500 shrink-0 mt-0.5" />
                {{ feature }}
              </li>
            </ul>
          </div>

          <!-- Price and Purchase -->
          <div class="bg-neutral-800/50 border border-neutral-700 rounded-lg p-4 flex items-center justify-between">
            <div>
              <p class="text-sm text-neutral-400 mb-1">One-time purchase</p>
              <p class="text-2xl font-bold text-oxide-400">${{ safeFixed(selectedModule.price, 2) }}</p>
            </div>
            <button
              v-if="!selectedModule.is_purchased"
              @click="initiatePurchase(selectedModule)"
              class="px-6 py-3 text-sm font-medium text-white bg-oxide-600 hover:bg-oxide-700 rounded-lg transition-colors"
            >
              Purchase Now
            </button>
            <button
              v-else-if="!selectedModule.is_installed"
              @click="installModule(selectedModule)"
              class="flex items-center gap-2 px-6 py-3 text-sm font-medium text-green-400 bg-green-500/10 hover:bg-green-500/20 border border-green-500/20 rounded-lg transition-colors"
            >
              <Download class="w-4 h-4" />
              Install
            </button>
            <div v-else class="flex items-center gap-2 text-green-400">
              <Check class="w-5 h-5" />
              <span class="text-sm font-medium">Installed</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Purchase Confirmation Modal -->
    <div
      v-if="showPurchaseModal && selectedModule"
      class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
      @click.self="closeModals"
    >
      <div class="bg-neutral-900 border border-neutral-800 rounded-lg max-w-md w-full">
        <!-- Header -->
        <div class="border-b border-neutral-800 px-6 py-4">
          <h2 class="text-xl font-bold text-neutral-100">Confirm Purchase</h2>
        </div>

        <!-- Body -->
        <div class="p-6 space-y-4">
          <div class="bg-neutral-800/50 border border-neutral-700 rounded-lg p-4 space-y-2">
            <div class="flex items-center justify-between">
              <span class="text-sm text-neutral-400">Module</span>
              <span class="text-sm font-medium text-neutral-100">{{ selectedModule.name }}</span>
            </div>
            <div class="flex items-center justify-between">
              <span class="text-sm text-neutral-400">License</span>
              <span class="text-sm font-medium text-neutral-100">{{ auth.license?.license_key }}</span>
            </div>
            <div class="border-t border-neutral-700 pt-2 mt-2 flex items-center justify-between">
              <span class="text-base font-medium text-neutral-300">Total</span>
              <span class="text-2xl font-bold text-oxide-400">${{ safeFixed(selectedModule.price, 2) }}</span>
            </div>
          </div>

          <div v-if="purchaseError" class="flex items-start gap-2 bg-red-500/10 border border-red-500/20 rounded-lg p-3">
            <AlertCircle class="w-4 h-4 text-red-400 shrink-0 mt-0.5" />
            <p class="text-sm text-red-400">{{ purchaseError }}</p>
          </div>

          <p class="text-xs text-neutral-500 leading-relaxed">
            By confirming this purchase, you agree to the module license terms. This purchase is non-refundable once the module is installed.
          </p>
        </div>

        <!-- Footer -->
        <div class="border-t border-neutral-800 px-6 py-4 flex items-center justify-end gap-3">
          <button
            @click="closeModals"
            :disabled="isPurchasing"
            class="px-4 py-2 text-sm font-medium text-neutral-300 bg-neutral-800 hover:bg-neutral-700 rounded-lg transition-colors disabled:opacity-50"
          >
            Cancel
          </button>
          <button
            @click="confirmPurchase"
            :disabled="isPurchasing"
            class="px-6 py-2 text-sm font-medium text-white bg-oxide-600 hover:bg-oxide-700 rounded-lg transition-colors disabled:opacity-50"
          >
            {{ isPurchasing ? 'Processing...' : 'Confirm Purchase' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
