<script setup lang="ts">
import { AlertTriangle, GitBranch, HardDrive, Package, Plus } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import type { Version } from '@/pages/admin/versions/data/schema'

import ConfirmDialog from '@/components/confirm-dialog.vue'
import SingleFilter from '@/components/data-table/single-filter.vue'
import { BasicPage } from '@/components/global-layout'
import DataTable from '@/pages/admin/versions/components/data-table.vue'
import api, { BASE_URL } from '@/services/api'

const { t } = useI18n()

interface Application {
  id: number
  name: string
}

const route = useRoute()
const router = useRouter()

const loading = ref(true)
const versions = ref<Version[]>([])
const applications = ref<Application[]>([])
const tableRef = ref()

const appFilter = ref<string>('')
const strategyFilter = ref<string>('')
const methodFilter = ref<string>('')
const searchFilter = ref<string>('')

const deleteDialogOpen = ref(false)
const deleteTarget = ref<Version | null>(null)
const batchDeleteDialogOpen = ref(false)
const batchDeleteIds = ref<number[]>([])

const applicationOptions = computed(() => {
  return applications.value.map(app => ({
    label: app.name,
    value: String(app.id),
  }))
})

const strategyOptions = computed(() => [
  { label: t('admin.versions.strategies.optional'), value: 'optional' },
  { label: t('admin.versions.strategies.forced'), value: 'forced' },
])

const methodOptions = computed(() => [
  { label: t('admin.versions.methods.manual'), value: 'manual' },
  { label: t('admin.versions.methods.auto'), value: 'auto' },
])

const filteredVersions = computed(() => {
  let result = versions.value

  if (appFilter.value) {
    result = result.filter(v => String(v.application_id) === appFilter.value)
  }

  if (strategyFilter.value) {
    result = result.filter(v => v.update_strategy === strategyFilter.value)
  }

  if (methodFilter.value) {
    result = result.filter(v => v.update_method === methodFilter.value)
  }

  if (searchFilter.value) {
    const search = searchFilter.value.toLowerCase()
    result = result.filter(v =>
      v.version?.toLowerCase().includes(search)
      || v.description?.toLowerCase().includes(search)
      || v.application_name?.toLowerCase().includes(search),
    )
  }

  return result
})

const totalSize = computed(() => {
  return filteredVersions.value.reduce((sum, v) => sum + (v.file_size || 0), 0)
})

const forcedCount = computed(() => filteredVersions.value.filter(v => v.update_strategy === 'forced').length)

function formatFileSize(bytes: number): string {
  if (bytes === 0)
    return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`
}

async function fetchApplications() {
  try {
    const data = await api.get<{ applications: Application[] }>('/dev/applications')
    applications.value = data?.applications || []
  }
  catch (error) {
    console.error('获取应用列表失败:', error)
  }
}

async function fetchVersions() {
  loading.value = true
  try {
    const data = await api.get<{ versions: Version[], total: number }>('/dev/versions')
    versions.value = data?.versions || []
  }
  catch (error) {
    console.error('加载版本列表失败:', error)
    versions.value = []
  }
  finally {
    loading.value = false
  }
}

function goToCreate() {
  router.push('/admin/versions/create')
}

function goToEdit(version: Version) {
  router.push(`/admin/versions/${version.id}`)
}

function downloadVersion(version: Version) {
  if (!version.file_path)
    return
  const token = localStorage.getItem('token')
  const downloadUrl = `${version.file_path}?token=${token}`
  window.open(downloadUrl, '_blank')
}

function confirmDelete(version: Version) {
  deleteTarget.value = version
  deleteDialogOpen.value = true
}

async function handleDelete() {
  if (!deleteTarget.value)
    return

  try {
    await api.delete(`/dev/applications/${deleteTarget.value.application_id}/versions/${deleteTarget.value.id}`)
    toast.success(t('admin.versions.deleteSuccess'))
    fetchVersions()
  }
  catch (error: any) {
    console.error('删除版本失败:', error)
    toast.error(error.message || t('common.error'))
  }
  finally {
    deleteTarget.value = null
  }
}

function handleExport() {
  const token = localStorage.getItem('token')
  const params = new URLSearchParams()
  if (appFilter.value)
    params.append('application_id', appFilter.value)
  if (strategyFilter.value)
    params.append('update_strategy', strategyFilter.value)
  if (methodFilter.value)
    params.append('update_method', methodFilter.value)

  const queryString = params.toString()
  const url = `${BASE_URL}/dev/versions/export?${queryString}&token=${token}`
  window.open(url, '_blank')
}

function handleBatchExport(ids: number[]) {
  if (!ids.length)
    return
  const token = localStorage.getItem('token')
  const params = new URLSearchParams()
  params.append('ids', ids.join(','))
  const url = `${BASE_URL}/dev/versions/export?${params.toString()}&token=${token}`
  window.open(url, '_blank')
}

function confirmBatchDelete(ids: number[]) {
  batchDeleteIds.value = ids
  batchDeleteDialogOpen.value = true
}

async function handleBatchDelete() {
  try {
    await api.delete('/dev/versions/batch', { ids: batchDeleteIds.value } as any)
    toast.success(t('admin.versions.batchDeleteSuccess'))
    fetchVersions()
  }
  catch (error: any) {
    console.error('批量删除失败:', error)
    toast.error(error.message || t('common.error'))
  }
  finally {
    batchDeleteIds.value = []
  }
}

onMounted(() => {
  fetchApplications()
  fetchVersions()
  const appParam = route.query.app as string
  if (appParam) {
    appFilter.value = appParam
  }
})
</script>

<template>
  <BasicPage
    :title="t('admin.versions.title')"
    :description="t('admin.versions.description')"
    sticky
  >
    <template #actions>
      <UiButton @click="goToCreate">
        <Plus class="mr-2 h-4 w-4" />
        {{ t('admin.versions.create') }}
      </UiButton>
    </template>

    <div class="space-y-6">
      <div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('admin.versions.totalVersions') }}
            </UiCardTitle>
            <GitBranch class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ filteredVersions.length }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('admin.versions.forcedCount') }}
            </UiCardTitle>
            <AlertTriangle class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ forcedCount }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('admin.versions.totalSize') }}
            </UiCardTitle>
            <HardDrive class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ formatFileSize(totalSize) }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('admin.versions.appCount') }}
            </UiCardTitle>
            <Package class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ new Set(filteredVersions.map(v => v.application_id)).size }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            ref="tableRef"
            :loading
            :data="filteredVersions"
            :on-download="downloadVersion"
            :on-edit="goToEdit"
            :on-delete="confirmDelete"
            :search-filter="searchFilter"
            @refresh="fetchVersions"
            @update:search-filter="searchFilter = $event"
            @export="handleExport"
            @batch-delete="confirmBatchDelete(tableRef?.table?.getSelectedRowModel().rows.map((r: any) => r.original.id) || [])"
            @batch-export="handleBatchExport(tableRef?.table?.getSelectedRowModel().rows.map((r: any) => r.original.id) || [])"
          >
            <template #filters>
              <SingleFilter
                v-model="appFilter"
                :title="t('admin.versions.application')"
                :options="applicationOptions"
              />
              <SingleFilter
                v-model="strategyFilter"
                :title="t('admin.versions.strategy')"
                :options="strategyOptions"
              />
              <SingleFilter
                v-model="methodFilter"
                :title="t('admin.versions.method')"
                :options="methodOptions"
              />
            </template>
          </DataTable>
        </UiCardContent>
      </UiCard>
    </div>

    <ConfirmDialog
      v-model:open="deleteDialogOpen"
      destructive
      :confirm-button-text="t('common.delete')"
      :cancel-button-text="t('common.cancel')"
      @confirm="handleDelete"
    >
      <template #title>
        {{ t('admin.versions.deleteVersion') }}
      </template>
      <template #description>
        {{ t('admin.versions.deleteConfirm', { version: deleteTarget?.version }) }}
      </template>
    </ConfirmDialog>

    <ConfirmDialog
      v-model:open="batchDeleteDialogOpen"
      destructive
      :confirm-button-text="t('common.delete')"
      :cancel-button-text="t('common.cancel')"
      @confirm="handleBatchDelete"
    >
      <template #title>
        {{ t('admin.versions.batchDelete') }}
      </template>
      <template #description>
        {{ t('admin.versions.batchDeleteConfirm', { count: batchDeleteIds.length }) }}
      </template>
    </ConfirmDialog>
  </BasicPage>
</template>
