<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 { safeFixed } from '@/utils/formatters'
import Panel from '@/components/ds/data/Panel.vue'
import Button from '@/components/ds/core/Button.vue'
import Badge from '@/components/ds/core/Badge.vue'
import Icon from '@/components/ds/core/Icon.vue'
import IconButton from '@/components/ds/core/IconButton.vue'
import Tabs from '@/components/ds/navigation/Tabs.vue'
import Alert from '@/components/ds/feedback/Alert.vue'
import EmptyState from '@/components/ds/feedback/EmptyState.vue'
import Input from '@/components/ds/forms/Input.vue'
import Select from '@/components/ds/forms/Select.vue'

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 tabItems = computed(() => [
  { value: 'catalog', label: 'Catalog', icon: 'package' },
  { value: 'my-modules', label: `My modules (${myModules.value.length})`, icon: 'download' },
])

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

type BadgeTone = 'info' | 'accent' | 'warn' | 'online' | 'neutral' | 'offline'
function categoryTone(category: string): BadgeTone {
  const map: Record<string, BadgeTone> = {
    loot: 'warn',
    events: 'accent',
    economy: 'online',
    kits: 'info',
    admin: 'accent',
    pvp: 'offline',
    pve: 'info',
    building: 'warn',
  }
  return map[category] ?? 'neutral'
}

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) {
      window.location.href = response.payment_url
    } else if (response.success) {
      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 = ''
}

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

<template>
  <div class="ms-page">
    <!-- Page head -->
    <div class="page__head">
      <div>
        <div class="t-eyebrow">Management</div>
        <h1 class="page__title">Module store</h1>
        <p class="page__sub">Extend your server with premium gameplay modules.</p>
      </div>
      <Tabs v-model="activeTab" :items="tabItems" />
    </div>

    <!-- Filters bar -->
    <div class="ms-filters">
      <Input
        v-model="searchQuery"
        icon="search"
        placeholder="Search modules…"
        class="ms-filters__search"
      />
      <Select
        v-model="selectedCategory"
        :options="categories"
        size="md"
        class="ms-filters__cat"
      />
    </div>

    <!-- Loading state -->
    <div v-if="isLoading" class="ms-loading">
      <EmptyState icon="loader" title="Loading modules…" />
    </div>

    <!-- Module grid -->
    <div v-else-if="filteredModules.length > 0" class="ms-grid">
      <article
        v-for="module in filteredModules"
        :key="module.id"
        class="ms-card"
      >
        <!-- Preview image -->
        <div class="ms-card__img">
          <img
            v-if="module.preview_image_url"
            :src="module.preview_image_url"
            :alt="module.name"
            class="ms-card__img-el"
          />
          <div v-else class="ms-card__img-placeholder">
            <Icon name="package" :size="36" :stroke-width="1.5" />
          </div>
          <div class="ms-card__img-badges">
            <Badge :tone="categoryTone(module.category)" size="md">{{ module.category }}</Badge>
          </div>
          <div v-if="module.is_purchased" class="ms-card__img-owned">
            <Badge tone="online" icon="check" size="md">Purchased</Badge>
          </div>
        </div>

        <!-- Content -->
        <div class="ms-card__body">
          <div class="ms-card__header">
            <span class="ms-card__name">{{ module.name }}</span>
            <span class="ms-price">${{ safeFixed(module.price, 2) }}</span>
          </div>
          <p class="ms-card__desc">{{ module.description }}</p>

          <!-- Features -->
          <div class="ms-card__features">
            <Badge
              v-for="(feature, idx) in module.features.slice(0, 3)"
              :key="idx"
              tone="neutral"
            >{{ feature }}</Badge>
            <span v-if="module.features.length > 3" class="ms-card__more">+{{ module.features.length - 3 }} more</span>
          </div>

          <!-- Actions -->
          <div class="ms-card__actions">
            <Button variant="secondary" size="sm" :block="false" @click="openDetailModal(module)">Details</Button>
            <Button
              v-if="!module.is_purchased"
              size="sm"
              @click="initiatePurchase(module)"
            >Purchase</Button>
            <Button
              v-else-if="!module.is_installed"
              size="sm"
              variant="outline"
              icon="download"
              @click="installModule(module)"
            >Install</Button>
            <Button
              v-else
              size="sm"
              variant="outline"
              icon="check"
              :disabled="true"
            >Installed</Button>
          </div>
        </div>
      </article>
    </div>

    <!-- Empty state -->
    <Panel v-else>
      <EmptyState
        icon="package"
        :title="activeTab === 'catalog' ? 'No modules found' : 'No purchased modules'"
        :description="activeTab === 'catalog' ? 'Try adjusting your search or category filter.' : 'Browse the catalog to purchase modules.'"
      />
    </Panel>

    <!-- ===== Detail modal ===== -->
    <div
      v-if="showDetailModal && selectedModule"
      class="ms-modal-backdrop"
      @click.self="closeModals"
    >
      <div class="ms-modal ms-modal--wide">
        <div class="ms-modal__head ms-modal__head--sticky">
          <div class="ms-modal__head-content">
            <div class="ms-modal__title-row">
              <h2 class="ms-modal__title">{{ selectedModule.name }}</h2>
              <Badge :tone="categoryTone(selectedModule.category)" size="md">{{ selectedModule.category }}</Badge>
            </div>
            <p class="ms-modal__ver">Version {{ selectedModule.version }}</p>
          </div>
          <IconButton icon="x" label="Close" @click="closeModals" />
        </div>

        <div class="ms-modal__body">
          <!-- Screenshots -->
          <div v-if="selectedModule.screenshots.length > 0" class="ms-detail-section">
            <div class="ms-detail-section__label">Screenshots</div>
            <div class="ms-screenshots">
              <img
                v-for="(screenshot, idx) in selectedModule.screenshots"
                :key="idx"
                :src="screenshot"
                :alt="`Screenshot ${idx + 1}`"
                class="ms-screenshot"
              />
            </div>
          </div>

          <!-- Description -->
          <div class="ms-detail-section">
            <div class="ms-detail-section__label">Description</div>
            <p class="ms-detail-desc">{{ selectedModule.description }}</p>
          </div>

          <!-- Features -->
          <div class="ms-detail-section">
            <div class="ms-detail-section__label">Features</div>
            <ul class="ms-features">
              <li v-for="(feature, idx) in selectedModule.features" :key="idx" class="ms-feature">
                <Icon name="check" :size="14" :stroke-width="2.5" class="ms-feature__icon" />
                {{ feature }}
              </li>
            </ul>
          </div>

          <!-- Price and action -->
          <div class="ms-detail-cta">
            <div>
              <p class="ms-detail-cta__label">One-time purchase</p>
              <p class="ms-price ms-price--lg">${{ safeFixed(selectedModule.price, 2) }}</p>
            </div>
            <Button
              v-if="!selectedModule.is_purchased"
              @click="initiatePurchase(selectedModule)"
            >Purchase now</Button>
            <Button
              v-else-if="!selectedModule.is_installed"
              variant="outline"
              icon="download"
              @click="installModule(selectedModule)"
            >Install</Button>
            <div v-else class="ms-installed">
              <Icon name="check" :size="18" :stroke-width="2.5" />
              <span>Installed</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- ===== Purchase confirmation modal ===== -->
    <div
      v-if="showPurchaseModal && selectedModule"
      class="ms-modal-backdrop"
      @click.self="closeModals"
    >
      <div class="ms-modal">
        <div class="ms-modal__head">
          <h2 class="ms-modal__title">Confirm purchase</h2>
          <IconButton icon="x" label="Close" @click="closeModals" />
        </div>

        <div class="ms-modal__body">
          <div class="ms-purchase-summary">
            <div class="ms-purchase-row">
              <span class="ms-purchase-row__label">Module</span>
              <span class="ms-purchase-row__value">{{ selectedModule.name }}</span>
            </div>
            <div class="ms-purchase-row">
              <span class="ms-purchase-row__label">License</span>
              <span class="ms-purchase-row__value ms-mono">{{ auth.license?.license_key }}</span>
            </div>
            <div class="ms-purchase-divider" />
            <div class="ms-purchase-row ms-purchase-row--total">
              <span class="ms-purchase-row__label">Total</span>
              <span class="ms-price ms-price--lg">${{ safeFixed(selectedModule.price, 2) }}</span>
            </div>
          </div>

          <Alert v-if="purchaseError" tone="danger">{{ purchaseError }}</Alert>

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

        <div class="ms-modal__foot">
          <Button variant="secondary" :disabled="isPurchasing" @click="closeModals">Cancel</Button>
          <Button :loading="isPurchasing" @click="confirmPurchase">Confirm purchase</Button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.ms-page { max-width: 1320px; margin: 0 auto; display: flex; flex-direction: column; gap: 20px; }

.page__head {
  display: flex; align-items: flex-end; justify-content: space-between;
  gap: 16px; flex-wrap: wrap; row-gap: 12px;
}
.page__title {
  font-size: var(--text-3xl); font-weight: 700; letter-spacing: -0.02em;
  color: var(--text-primary); margin-top: 5px;
}
.page__sub { font-size: var(--text-sm); color: var(--text-tertiary); margin-top: 3px; }

/* Filters */
.ms-filters { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.ms-filters__search { flex: 1; min-width: 200px; max-width: 380px; }
.ms-filters__cat { min-width: 160px; }

.ms-loading { padding: 20px 0; }

/* Module grid */
.ms-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 16px; }

/* Module card */
.ms-card {
  background: var(--surface-base); border-radius: var(--radius-lg);
  box-shadow: var(--ring-default); overflow: hidden; display: flex; flex-direction: column;
  transition: box-shadow var(--dur-base) var(--ease-standard);
}
.ms-card:hover { box-shadow: inset 0 0 0 1px var(--accent-border), var(--ring-default); }

.ms-card__img {
  position: relative; height: 160px; overflow: hidden;
  background: var(--surface-inset);
}
.ms-card__img-el {
  width: 100%; height: 100%; object-fit: cover;
  transition: transform 300ms var(--ease-standard);
}
.ms-card:hover .ms-card__img-el { transform: scale(1.04); }
.ms-card__img-placeholder {
  width: 100%; height: 100%; display: flex; align-items: center; justify-content: center;
  color: var(--text-muted);
}
.ms-card__img-badges { position: absolute; top: 8px; right: 8px; }
.ms-card__img-owned { position: absolute; top: 8px; left: 8px; }

.ms-card__body { padding: 14px 16px; display: flex; flex-direction: column; gap: 10px; flex: 1; }
.ms-card__header { display: flex; align-items: flex-start; justify-content: space-between; gap: 8px; }
.ms-card__name { font-size: var(--text-base); font-weight: 600; color: var(--text-primary); }
.ms-card__desc { font-size: var(--text-sm); color: var(--text-tertiary); line-height: 1.5; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.ms-card__features { display: flex; flex-wrap: wrap; gap: 4px; align-items: center; }
.ms-card__more { font-size: var(--text-xs); color: var(--text-muted); }
.ms-card__actions { display: flex; gap: 8px; margin-top: auto; padding-top: 4px; }

/* Price — mono + tabular */
.ms-price { font-family: var(--font-mono); font-variant-numeric: tabular-nums; font-weight: 700; font-size: var(--text-base); color: var(--accent-text); }
.ms-price--lg { font-size: var(--text-2xl); }
.ms-mono { font-family: var(--font-mono); font-size: var(--text-xs); font-variant-numeric: tabular-nums; }

/* Modal */
.ms-modal-backdrop {
  position: fixed; inset: 0; z-index: 60;
  display: flex; align-items: center; justify-content: center;
  background: rgba(0,0,0,.6); backdrop-filter: blur(4px); padding: 16px;
}
.ms-modal {
  background: var(--surface-base); border-radius: var(--radius-lg);
  box-shadow: var(--shadow-xl, var(--ring-default)); max-width: 480px; width: 100%;
  display: flex; flex-direction: column; max-height: 90vh;
}
.ms-modal--wide { max-width: 760px; }

.ms-modal__head {
  display: flex; align-items: flex-start; justify-content: space-between;
  padding: 16px 20px; border-bottom: 1px solid var(--border-subtle); flex: none;
}
.ms-modal__head--sticky { position: sticky; top: 0; background: var(--surface-base); z-index: 1; }
.ms-modal__head-content { flex: 1; min-width: 0; }
.ms-modal__title-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.ms-modal__title { font-size: var(--text-lg); font-weight: 700; color: var(--text-primary); }
.ms-modal__ver { font-family: var(--font-mono); font-size: var(--text-xs); color: var(--text-muted); margin-top: 3px; }

.ms-modal__body { padding: 20px; overflow-y: auto; display: flex; flex-direction: column; gap: 20px; }
.ms-modal__foot {
  display: flex; align-items: center; justify-content: flex-end;
  gap: 8px; padding: 14px 20px; border-top: 1px solid var(--border-subtle); flex: none;
}

/* Detail modal content */
.ms-detail-section { display: flex; flex-direction: column; gap: 10px; }
.ms-detail-section__label {
  font-size: var(--text-xs); font-weight: 600; color: var(--text-muted);
  text-transform: uppercase; letter-spacing: var(--tracking-wider);
}
.ms-detail-desc { font-size: var(--text-sm); color: var(--text-secondary); line-height: 1.6; }

.ms-screenshots { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.ms-screenshot { width: 100%; height: 180px; object-fit: cover; border-radius: var(--radius-md); box-shadow: var(--ring-default); }

.ms-features { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
.ms-feature { display: flex; align-items: flex-start; gap: 8px; font-size: var(--text-sm); color: var(--text-secondary); }
.ms-feature__icon { flex: none; color: var(--accent-text); margin-top: 2px; }

.ms-detail-cta {
  display: flex; align-items: center; justify-content: space-between; gap: 16px;
  background: var(--surface-raised); border-radius: var(--radius-md);
  box-shadow: var(--ring-default); padding: 14px 16px;
}
.ms-detail-cta__label { font-size: var(--text-xs); color: var(--text-tertiary); margin-bottom: 4px; }

.ms-installed {
  display: flex; align-items: center; gap: 8px;
  font-size: var(--text-sm); font-weight: 500; color: var(--status-online);
}

/* Purchase summary */
.ms-purchase-summary {
  background: var(--surface-raised); border-radius: var(--radius-md);
  box-shadow: var(--ring-default); padding: 14px 16px;
  display: flex; flex-direction: column; gap: 10px;
}
.ms-purchase-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.ms-purchase-row--total { margin-top: 2px; }
.ms-purchase-row__label { font-size: var(--text-sm); color: var(--text-tertiary); }
.ms-purchase-row__value { font-size: var(--text-sm); font-weight: 500; color: var(--text-primary); }
.ms-purchase-divider { height: 1px; background: var(--border-subtle); }

.ms-purchase-terms { font-size: var(--text-xs); color: var(--text-muted); line-height: 1.5; }

/* Responsive */
@media (max-width: 768px) {
  .ms-grid { grid-template-columns: 1fr; }
  .ms-filters__search { max-width: 100%; }
}
</style>
