<template>
  <div class="p-6">
    <div class="mb-8">
      <h1 class="text-3xl font-bold text-white mb-2">My Apps</h1>
      <p class="text-white/70">Manage your Archipelago applications</p>
    </div>

    <!-- Loading State (initial load) -->
    <div v-if="store.loading && !hasAnyApps" class="flex items-center justify-center py-12">
      <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-white/60"></div>
    </div>

    <!-- Error State -->
    <div v-if="store.error" class="glass-card p-6 mb-6">
      <div class="flex items-center gap-3 text-red-400">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
        <span>{{ store.error }}</span>
      </div>
    </div>

    <!-- Apps Grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <!-- Bundled Apps -->
      <div
        v-for="app in bundledApps"
        :key="app.id"
        data-controller-container
        tabindex="0"
        class="glass-card p-6 hover:bg-white/5 transition-colors"
      >
        <div class="flex items-start justify-between mb-4">
          <div class="flex items-center gap-3">
            <span class="text-3xl">{{ app.icon }}</span>
            <div>
              <h3 class="text-lg font-semibold text-white">{{ app.name }}</h3>
              <p class="text-sm text-white/60">{{ app.description }}</p>
            </div>
          </div>
        </div>

        <!-- Status Badge -->
        <div class="mb-4">
          <span 
            :class="getStatusBadgeClass(app.id)"
            class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium"
          >
            <!-- Loading spinner -->
            <svg 
              v-if="store.isAppLoading(app.id)" 
              class="w-3 h-3 animate-spin" 
              fill="none" 
              viewBox="0 0 24 24"
            >
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            <!-- Status dot -->
            <span 
              v-else
              :class="getStatusDotClass(app.id)"
              class="w-2 h-2 rounded-full"
            ></span>
            {{ getStatusText(app.id) }}
          </span>
        </div>

        <!-- Port info -->
        <div class="text-sm text-white/50 mb-4">
          <span v-if="store.getAppState(app.id) === 'running'">
            Port{{ app.ports.length > 1 ? 's' : '' }}: 
            {{ app.ports.map(p => p.host).join(', ') }}
          </span>
          <span v-else>
            {{ app.image.split('/').pop() }}
          </span>
        </div>

        <!-- Action Buttons -->
        <div class="flex gap-2">
          <!-- Not installed: Start button -->
          <button
            v-if="store.getAppState(app.id) === 'not-installed'"
            @click="handleStartApp(app)"
            :disabled="store.isAppLoading(app.id)"
            class="flex-1 px-4 py-2 bg-green-600 hover:bg-green-500 disabled:bg-green-800 disabled:cursor-not-allowed rounded text-sm font-medium text-white transition-colors flex items-center justify-center gap-2"
          >
            <svg v-if="store.isAppLoading(app.id)" class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            <span>{{ store.isAppLoading(app.id) ? 'Starting...' : 'Start' }}</span>
          </button>

          <!-- Stopped: Start button -->
          <button
            v-else-if="store.getAppState(app.id) === 'stopped' || store.getAppState(app.id) === 'exited'"
            @click="handleStartApp(app)"
            :disabled="store.isAppLoading(app.id)"
            class="flex-1 px-4 py-2 bg-green-600 hover:bg-green-500 disabled:bg-green-800 disabled:cursor-not-allowed rounded text-sm font-medium text-white transition-colors flex items-center justify-center gap-2"
          >
            <svg v-if="store.isAppLoading(app.id)" class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            <span>{{ store.isAppLoading(app.id) ? 'Starting...' : 'Start' }}</span>
          </button>

          <!-- Starting (created): show progress, no Launch yet -->
          <div
            v-else-if="store.getAppState(app.id) === 'created'"
            class="flex-1 flex items-center justify-center gap-2 px-4 py-2 text-white/70 text-sm"
          >
            <svg class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            <span>Starting…</span>
          </div>

          <!-- Running: Stop and Launch buttons -->
          <template v-else-if="store.getAppState(app.id) === 'running'">
            <button
              @click="handleStopApp(app.id)"
              :disabled="store.isAppLoading(app.id)"
              class="flex-1 px-4 py-2 glass-button rounded text-sm font-medium text-white/90 hover:text-white disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2"
            >
              <svg v-if="store.isAppLoading(app.id)" class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              <span>{{ store.isAppLoading(app.id) ? 'Stopping...' : 'Stop' }}</span>
            </button>
            <button
              type="button"
              class="px-4 py-2 bg-blue-600 hover:bg-blue-500 rounded text-sm font-medium text-white transition-colors flex items-center gap-2"
              @click="launchApp(app)"
            >
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
              </svg>
              Launch
            </button>
          </template>
        </div>
      </div>

      <!-- Other containers (not bundled) -->
      <div
        v-for="container in otherContainers"
        :key="container.id"
        data-controller-container
        tabindex="0"
        class="glass-card p-6 hover:bg-white/5 transition-colors"
      >
        <div class="flex items-start justify-between mb-4">
          <div class="flex items-center gap-3">
            <span class="text-3xl">📦</span>
            <div>
              <h3 class="text-lg font-semibold text-white">{{ extractAppName(container.name) }}</h3>
              <p class="text-sm text-white/60">{{ container.image }}</p>
            </div>
          </div>
        </div>

        <div class="mb-4">
          <ContainerStatus :state="container.state as any" />
        </div>

        <div class="flex gap-2">
          <button
            v-if="container.state !== 'running'"
            @click="handleStartContainer(container.name)"
            class="flex-1 px-4 py-2 glass-button rounded text-sm font-medium text-white/90 hover:text-white transition-colors"
          >
            Start
          </button>
          <button
            v-else
            @click="handleStopContainer(container.name)"
            class="flex-1 px-4 py-2 glass-button rounded text-sm font-medium text-white/90 hover:text-white transition-colors"
          >
            Stop
          </button>
        </div>
      </div>
    </div>

    <!-- Empty state (when no bundled apps - shouldn't happen) -->
    <div v-if="!hasAnyApps && !store.loading" class="glass-card p-12 text-center">
      <svg class="w-16 h-16 mx-auto mb-4 text-white/40" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
      </svg>
      <h3 class="text-xl font-semibold text-white mb-2">No apps available</h3>
      <p class="text-white/60">Check your Archipelago installation</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, computed } from 'vue'
import { useContainerStore, type BundledApp } from '@/stores/container'
import { useAppLauncherStore } from '@/stores/appLauncher'
import ContainerStatus from '@/components/ContainerStatus.vue'

const store = useContainerStore()
const appLauncherStore = useAppLauncherStore()

// Use enriched bundled apps with runtime data (like lan_address)
const bundledApps = computed(() => store.enrichedBundledApps)

// Get current host for launch URLs
const currentHost = computed(() => window.location.hostname)

let startingPollInterval: ReturnType<typeof setInterval> | null = null

onMounted(async () => {
  await store.fetchContainers()
  await store.fetchHealthStatus()

  // Refresh every 10 seconds
  setInterval(async () => {
    await store.fetchContainers()
    await store.fetchHealthStatus()
  }, 10000)

  // When any bundled app is in 'created' (starting), poll every 2s so state updates to running
  startingPollInterval = setInterval(async () => {
    const anyStarting = bundledApps.value.some((app) => store.getAppState(app.id) === 'created')
    if (anyStarting) {
      await store.fetchContainers()
      await store.fetchHealthStatus()
    }
  }, 2000)
})

onUnmounted(() => {
  if (startingPollInterval) clearInterval(startingPollInterval)
})

// Containers that aren't bundled apps
const otherContainers = computed(() => {
  const bundledIds = bundledApps.value.map(a => a.id)
  return store.containers.filter(c => {
    const name = c.name.toLowerCase()
    return !bundledIds.some(id => name.includes(id))
  })
})

const hasAnyApps = computed(() => bundledApps.value.length > 0 || store.containers.length > 0)

function extractAppName(containerName: string): string {
  return containerName
    .replace('archipelago-', '')
    .replace('-dev', '')
    .split('-')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ')
}

function getStatusBadgeClass(appId: string): string {
  if (store.isAppLoading(appId)) {
    return 'bg-yellow-500/20 text-yellow-400'
  }
  const state = store.getAppState(appId)
  switch (state) {
    case 'running':
      return 'bg-green-500/20 text-green-400'
    case 'stopped':
    case 'exited':
      return 'bg-gray-500/20 text-gray-400'
    case 'created':
      return 'bg-yellow-500/20 text-yellow-400'
    case 'not-installed':
    default:
      return 'bg-blue-500/20 text-blue-400'
  }
}

function getStatusDotClass(appId: string): string {
  const state = store.getAppState(appId)
  switch (state) {
    case 'running':
      return 'bg-green-400'
    case 'stopped':
    case 'exited':
      return 'bg-gray-400'
    case 'not-installed':
    default:
      return 'bg-blue-400'
  }
}

function getStatusText(appId: string): string {
  if (store.isAppLoading(appId)) {
    return 'Loading...'
  }
  const state = store.getAppState(appId)
  switch (state) {
    case 'running':
      return 'Running'
    case 'stopped':
    case 'exited':
      return 'Stopped'
    case 'not-installed':
      return 'Ready to Start'
    case 'created':
      return 'Starting'
    default:
      return state
  }
}

const backendPort = 5678

function getLaunchUrl(app: BundledApp): string {
  // Prefer lan_address from backend (for apps with custom UIs)
  if (app.lan_address) {
    // Replace localhost so Launch works when browsing from another machine (e.g. 192.168.1.228)
    let url = app.lan_address.replace(/localhost/i, currentHost.value)
    // LND UI (and other app UIs) need backend URL for live data (logs, getinfo proxy)
    if (app.id === 'lnd') {
      const backend = `http://${currentHost.value}:${backendPort}`
      url += (url.includes('?') ? '&' : '?') + 'backend=' + encodeURIComponent(backend)
    }
    return url
  }

  // Fallback to first configured port
  const port = app.ports[0]?.host
  if (!port) return '#'
  return `http://${currentHost.value}:${port}`
}

function launchApp(app: BundledApp) {
  const url = getLaunchUrl(app)
  if (url === '#') return
  appLauncherStore.open({ url, title: app.name })
}

async function handleStartApp(app: BundledApp) {
  try {
    await store.startBundledApp(app)
  } catch (e) {
    console.error('Failed to start app:', e)
  }
}

async function handleStopApp(appId: string) {
  try {
    await store.stopBundledApp(appId)
  } catch (e) {
    console.error('Failed to stop app:', e)
  }
}

async function handleStartContainer(name: string) {
  try {
    const appId = name.replace('archipelago-', '').replace('-dev', '')
    await store.startContainer(appId)
  } catch (e) {
    console.error('Failed to start container:', e)
  }
}

async function handleStopContainer(name: string) {
  try {
    const appId = name.replace('archipelago-', '').replace('-dev', '')
    await store.stopContainer(appId)
  } catch (e) {
    console.error('Failed to stop container:', e)
  }
}
</script>
