<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { fetchModules, manageModule } from '@/services/moduleService'
import type { Module, ModuleAction } from '@/types/module'

const modules = ref<Module[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const actionLoading = ref<string | null>(null)
const snackbar = ref(false)
const snackbarText = ref('')
const snackbarColor = ref('success')
const search = ref('')
const filterStatus = ref<string>('all')

const upgradeCount = computed(() => modules.value.filter(m => m.needsUpgrade).length)

const statusFilters = computed(() => [
  { title: 'All', value: 'all' as const, count: modules.value.length },
  { title: 'Installed', value: 'installed' as const, count: modules.value.filter(m => m.installed).length },
  { title: 'Not Installed', value: 'not-installed' as const, count: modules.value.filter(m => !m.installed).length },
  { title: 'Enabled', value: 'enabled' as const, count: modules.value.filter(m => m.enabled).length },
  { title: 'Disabled', value: 'disabled' as const, count: modules.value.filter(m => m.installed && !m.enabled).length },
])

const filteredModules = computed(() => {
  let result = modules.value

  // Filter by status
  const status = filterStatus.value
  if (status === 'installed') {
    result = result.filter(m => m.installed)
  } else if (status === 'not-installed') {
    result = result.filter(m => !m.installed)
  } else if (status === 'enabled') {
    result = result.filter(m => m.enabled)
  } else if (status === 'disabled') {
    result = result.filter(m => m.installed && !m.enabled)
  }

  // Filter by search
  const q = (search.value ?? '').trim().toLowerCase()
  if (q) {
    result = result.filter(
      m =>
        (m.handle ?? '').toLowerCase().includes(q) ||
        (m.label ?? '').toLowerCase().includes(q) ||
        (m.description ?? '').toLowerCase().includes(q) ||
        (m.author ?? '').toLowerCase().includes(q) ||
        (m.namespace ?? '').toLowerCase().includes(q)
    )
  }

  return result
})

async function loadModules() {
  loading.value = true
  error.value = null
  try {
    modules.value = await fetchModules()
  } catch (e) {
    error.value = e instanceof Error ? e.message : 'Failed to load modules'
  } finally {
    loading.value = false
  }
}

async function handleAction(module: Module, action: ModuleAction) {
  const key = `${module.handle}-${action}`
  actionLoading.value = key

  try {
    const result = await manageModule(module.handle, action)
    
    snackbarText.value = result.message || `Module ${action}ed successfully`
    snackbarColor.value = 'success'
    snackbar.value = true

    // Reload modules to get updated state
    await loadModules()
  } catch (e) {
    snackbarText.value = e instanceof Error ? e.message : `Failed to ${action} module`
    snackbarColor.value = 'error'
    snackbar.value = true
  } finally {
    actionLoading.value = null
  }
}

function getStatusColor(module: Module): string {
  if (!module.installed) return 'grey'
  if (module.enabled) return 'success'
  return 'warning'
}

function getStatusText(module: Module): string {
  if (!module.installed) return 'Not Installed'
  if (module.enabled) return 'Enabled'
  return 'Disabled'
}

function isActionLoading(module: Module, action: string): boolean {
  return actionLoading.value === `${module.handle}-${action}`
}

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

<template>
  <v-container fluid class="pa-4">
    <!-- Header -->
    <div class="d-flex align-center mb-6">
      <div class="d-flex align-center ga-3">
        <v-avatar color="primary" rounded="lg" size="44">
          <v-icon icon="mdi-package-variant" color="white"></v-icon>
        </v-avatar>
        <div>
          <h1 class="text-h5 font-weight-bold">Module Manager</h1>
          <p class="text-caption text-medium-emphasis mb-0">
            {{ modules.length }} module{{ modules.length !== 1 ? 's' : '' }} available
          </p>
        </div>
      </div>
      <v-spacer></v-spacer>
      <v-btn
        icon="mdi-refresh"
        variant="tonal"
        :loading="loading"
        @click="loadModules"
      ></v-btn>
    </div>

    <!-- Filters -->
    <div class="d-flex align-center ga-3 flex-wrap mb-4">
        <v-text-field
          v-model="search"
          prepend-inner-icon="mdi-magnify"
          label="Search modules"
          variant="outlined"
          density="compact"
          clearable
          hide-details
          style="min-width: 220px; max-width: 360px;"
        ></v-text-field>

        <v-btn-toggle
          v-model="filterStatus"
          density="compact"
          variant="outlined"
          color="primary"
          rounded="lg"
          mandatory
        >
          <v-btn
            v-for="filter in statusFilters"
            :key="filter.value"
            :value="filter.value"
            size="small"
          >
            {{ filter.title }} ({{ filter.count }})
          </v-btn>
        </v-btn-toggle>

        <v-spacer></v-spacer>

        <v-chip v-if="upgradeCount > 0" color="warning" variant="flat" size="small" prepend-icon="mdi-alert-circle">
          {{ upgradeCount }} upgrade{{ upgradeCount !== 1 ? 's' : '' }} available
        </v-chip>
    </div>

    <!-- Error -->
    <v-alert v-if="error" type="error" variant="tonal" class="mb-4" prepend-icon="mdi-alert-circle">
      {{ error }}
    </v-alert>

    <!-- Loading -->
    <v-progress-linear v-if="loading" indeterminate color="primary" class="mb-4" rounded></v-progress-linear>

    <!-- Module Grid -->
    <v-row v-else>
      <v-col
        v-for="module in filteredModules"
        :key="module.handle"
        cols="12"
        md="6"
        xl="4"
      >
        <v-card
          :class="['module-card', { 'module-card--upgrade': module.needsUpgrade }]"
          :border="module.needsUpgrade ? 'warning md' : true"
          rounded="lg"
        >
          <!-- Card Header -->
          <div class="module-card__header pa-4 d-flex align-start ga-3">

            <!-- Left: text content -->
            <div class="flex-grow-1 min-width-0">
              <div class="d-flex justify-start align-center ga-2 flex-wrap mb-1">
                <v-avatar
                  :color="getStatusColor(module)"
                  rounded="md"
                  size="28"
                  class="flex-shrink-0"
                >
                  <v-icon icon="mdi-package-variant" size="16" color="white"></v-icon>
                </v-avatar>
                <span class="text-subtitle-1 font-weight-semibold text-truncate">{{ module.label || module.handle }}</span>
                <span class="text-caption text-medium-emphasis flex-shrink-0">v{{ module.version }}</span>
                <v-chip
                  v-if="module.needsUpgrade"
                  color="warning"
                  size="x-small"
                  variant="flat"
                  class="flex-shrink-0"
                  prepend-icon="mdi-update"
                >
                  Update available
                </v-chip>
              </div>
              <div class="d-flex justify-start align-center ga-1 text-caption text-medium-emphasis mb-2">
                <v-icon icon="mdi-account" size="13"></v-icon>
                <span>{{ module.author || 'Unknown' }}</span>
              </div>
              <p class="text-body-1 mb-0 module-description">{{ module.description || 'No description provided.' }}</p>
            </div>

            <!-- Right: action buttons stacked -->
            <div class="d-flex flex-column ga-1 flex-shrink-0">
              <v-btn
                v-if="!module.installed"
                color="primary"
                variant="tonal"
                prepend-icon="mdi-download"
                :loading="isActionLoading(module, 'install')"
                @click="handleAction(module, 'install')"
              >
                Install
              </v-btn>

              <template v-if="module.installed">
                <v-btn
                  v-if="!module.enabled"
                  color="success"
                  variant="tonal"
                  prepend-icon="mdi-check-circle"
                  :loading="isActionLoading(module, 'enable')"
                  @click="handleAction(module, 'enable')"
                >
                  Enable
                </v-btn>

                <v-btn
                  v-if="module.enabled"
                  color="warning"
                  variant="tonal"
                  prepend-icon="mdi-close-circle"
                  :loading="isActionLoading(module, 'disable')"
                  @click="handleAction(module, 'disable')"
                >
                  Disable
                </v-btn>

                <v-btn
                  v-if="module.needsUpgrade"
                  color="warning"
                  variant="tonal"
                  prepend-icon="mdi-update"
                  :loading="isActionLoading(module, 'upgrade')"
                  @click="handleAction(module, 'upgrade')"
                >
                  Upgrade
                </v-btn>

                <v-btn
                  color="error"
                  variant="tonal"
                  prepend-icon="mdi-trash-can"
                  :loading="isActionLoading(module, 'uninstall')"
                  @click="handleAction(module, 'uninstall')"
                >
                  Uninstall
                </v-btn>
              </template>
            </div>
          </div>
        </v-card>
      </v-col>

      <v-col v-if="filteredModules.length === 0 && !loading" cols="12">
        <v-empty-state
          icon="mdi-package-variant"
          title="No modules found"
          text="Try adjusting your search or filter criteria."
        ></v-empty-state>
      </v-col>
    </v-row>

    <v-snackbar
      v-model="snackbar"
      :color="snackbarColor"
      :timeout="3000"
      location="bottom right"
    >
      {{ snackbarText }}
      <template #actions>
        <v-btn variant="text" @click="snackbar = false">Close</v-btn>
      </template>
    </v-snackbar>
  </v-container>
</template>

<style scoped lang="scss">
.module-card {
  display: flex;
  flex-direction: column;
  height: 100%;
  transition: box-shadow 0.2s ease;

  &:hover {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12) !important;
  }

  &__header {
    border-bottom: none;
    flex: 1;
  }

  .module-description {
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.cursor-pointer {
  cursor: pointer;
}

.min-width-0 {
  min-width: 0;
}
</style>
