<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useApi } from '@/composables/useApi'
import { useAuthStore } from '@/stores/auth'
import { useToastStore } from '@/stores/toast'
import type { MapEntry } from '@/types'
import { Map, Upload, Trash2, RefreshCw, Loader2 } from 'lucide-vue-next'
import { safeFileSize } from '@/utils/formatters'

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

const maps = ref<MapEntry[]>([])
const isLoading = ref(false)
const isUploading = ref(false)
const fileInputRef = ref<HTMLInputElement | null>(null)

function formatSize(bytes: number): string {
  return safeFileSize(bytes)
}

function typeBadgeClass(type: string): string {
  return type === 'custom' ? 'bg-oxide-500/15 text-oxide-400' : 'bg-blue-500/15 text-blue-400'
}

async function fetchMaps() {
  isLoading.value = true
  try {
    const data = await api.get<{ maps: MapEntry[] }>('/maps')
    maps.value = data.maps
  } catch {
    toast.error('Failed to load map library')
  } finally {
    isLoading.value = false
  }
}

async function deleteMap(map: MapEntry) {
  if (!confirm(`Delete ${map.display_name}?`)) return
  try {
    await api.del(`/maps/${map.id}`)
    await fetchMaps()
    toast.success(`${map.display_name} deleted`)
  } catch (err) {
    toast.error(err instanceof Error ? err.message : 'Failed to delete map')
  }
}

function triggerFileInput() {
  fileInputRef.value?.click()
}

async function handleFileSelected(event: Event) {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]
  if (!file) return

  // Reset the input so the same file can be re-selected if needed
  input.value = ''

  isUploading.value = true
  try {
    const formData = new FormData()
    formData.append('file', file)

    const response = await fetch('/api/maps', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${auth.accessToken}`,
      },
      body: formData,
    })

    if (!response.ok) {
      const err = await response.json().catch(() => ({ message: 'Upload failed' }))
      throw new Error(err.message || `HTTP ${response.status}`)
    }

    toast.success(`${file.name} uploaded successfully`)
    await fetchMaps()
  } catch (err) {
    toast.error(err instanceof Error ? err.message : 'Upload failed')
  } finally {
    isUploading.value = false
  }
}

onMounted(() => {
  fetchMaps()
})
</script>

<template>
  <div class="p-6 space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-3">
        <Map class="w-5 h-5 text-oxide-500" />
        <div>
          <h1 class="text-2xl font-bold text-neutral-100">Map Library</h1>
          <p class="text-sm text-neutral-500 mt-0.5">{{ maps.length }} maps</p>
        </div>
      </div>
      <div class="flex items-center gap-3">
        <button
          @click="fetchMaps"
          :disabled="isLoading"
          class="flex items-center gap-2 px-3 py-2 text-sm text-neutral-400 hover:text-neutral-200 bg-neutral-800 hover:bg-neutral-700 rounded-lg transition-colors"
        >
          <RefreshCw class="w-4 h-4" :class="{ 'animate-spin': isLoading }" />
        </button>
        <input
          ref="fileInputRef"
          type="file"
          accept=".map"
          class="hidden"
          @change="handleFileSelected"
        />
        <button
          @click="triggerFileInput"
          :disabled="isUploading"
          class="flex items-center gap-2 px-4 py-2 bg-oxide-600 hover:bg-oxide-700 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg transition-colors"
        >
          <Loader2 v-if="isUploading" class="w-4 h-4 animate-spin" />
          <Upload v-else class="w-4 h-4" />
          {{ isUploading ? 'Uploading...' : 'Upload Map' }}
        </button>
      </div>
    </div>

    <!-- Maps grid -->
    <div v-if="maps.length === 0" class="bg-neutral-900 border border-neutral-800 rounded-lg p-12 text-center">
      <Map class="w-10 h-10 text-neutral-600 mx-auto mb-3" />
      <h3 class="text-lg font-medium text-neutral-300 mb-1">No Maps</h3>
      <p class="text-sm text-neutral-500">Upload custom maps or they'll appear here when procedural maps are generated.</p>
    </div>

    <div v-else class="grid grid-cols-2 lg:grid-cols-3 gap-4">
      <div
        v-for="map in maps"
        :key="map.id"
        class="bg-neutral-900 border border-neutral-800 rounded-lg overflow-hidden hover:border-neutral-700 transition-colors"
      >
        <!-- Thumbnail or placeholder -->
        <div class="h-32 bg-neutral-800 flex items-center justify-center">
          <img v-if="map.thumbnail_path" :src="map.thumbnail_path" :alt="map.display_name" class="w-full h-full object-cover" />
          <Map v-else class="w-8 h-8 text-neutral-600" />
        </div>
        <div class="p-4">
          <div class="flex items-center justify-between mb-2">
            <h3 class="text-sm font-medium text-neutral-100 truncate">{{ map.display_name }}</h3>
            <span class="text-xs font-medium px-2 py-0.5 rounded-full shrink-0 ml-2" :class="typeBadgeClass(map.map_type)">
              {{ map.map_type }}
            </span>
          </div>
          <div class="flex items-center justify-between text-xs text-neutral-500">
            <span>{{ formatSize(map.file_size_bytes) }}</span>
            <span v-if="map.world_size">{{ map.world_size }}m</span>
            <span v-if="map.seed">Seed: {{ map.seed }}</span>
          </div>
          <div class="flex justify-end mt-3">
            <button
              @click="deleteMap(map)"
              class="p-1.5 text-neutral-500 hover:text-red-400 rounded transition-colors"
              title="Delete map"
            >
              <Trash2 class="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
