<script setup lang="ts">
import { CheckCircle, Database, Percent, Plus, XCircle } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import type { StorageConfig } from './data/schema'

import ConfirmDialog from '@/components/confirm-dialog.vue'
import { BasicPage } from '@/components/global-layout'
import DataTable from './components/data-table.vue'
import api from '@/services/api'

const router = useRouter()

const loading = ref(true)
const storageConfigs = ref<StorageConfig[]>([])
const tableRef = ref()

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

const activeCount = computed(() => storageConfigs.value.filter(c => c.status === 'active').length)
const inactiveCount = computed(() => storageConfigs.value.filter(c => c.status === 'inactive').length)

async function fetchStorageConfigs() {
  loading.value = true
  try {
    const data = await api.get<{ storage_configs: StorageConfig[] }>('/dev/storage-configs')
    storageConfigs.value = data?.storage_configs || []
  }
  catch (error) {
    console.error('加载存储配置失败:', error)
    storageConfigs.value = []
  }
  finally {
    loading.value = false
  }
}

function goToCreate() {
  router.push('/admin/storage-configs/create')
}

function goToEdit(config: StorageConfig) {
  router.push(`/admin/storage-configs/${config.id}`)
}

async function toggleStatus(config: StorageConfig) {
  const newStatus = config.status === 'active' ? 'inactive' : 'active'
  try {
    await api.put(`/dev/storage-configs/${config.id}/status`, { status: newStatus })
    toast.success('状态更新成功')
    fetchStorageConfigs()
  }
  catch (error: any) {
    console.error('更新状态失败:', error)
    toast.error(error.message || '更新失败')
  }
}

async function setDefault(config: StorageConfig) {
  try {
    await api.put(`/dev/storage-configs/${config.id}/default`)
    toast.success('已设为默认存储')
    fetchStorageConfigs()
  }
  catch (error: any) {
    console.error('设置默认失败:', error)
    toast.error(error.message || '设置失败')
  }
}

function confirmDelete(config: StorageConfig) {
  deleteTarget.value = config
  deleteDialogOpen.value = true
}

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

  try {
    await api.delete(`/dev/storage-configs/${deleteTarget.value.id}`)
    toast.success('删除成功')
    fetchStorageConfigs()
  }
  catch (error: any) {
    console.error('删除存储配置失败:', error)
    toast.error(error.message || '删除失败')
  }
  finally {
    deleteTarget.value = null
  }
}

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

async function handleBatchDelete() {
  try {
    await api.delete('/dev/storage-configs/batch', { ids: batchDeleteIds.value } as any)
    toast.success('批量删除成功')
    fetchStorageConfigs()
  }
  catch (error: any) {
    console.error('批量删除失败:', error)
    toast.error(error.message || '批量删除失败')
  }
  finally {
    batchDeleteIds.value = []
  }
}

async function batchToggleStatus(ids: number[], status: string) {
  try {
    await api.put('/dev/storage-configs/batch/status', { ids, status })
    toast.success('批量更新成功')
    fetchStorageConfigs()
  }
  catch (error: any) {
    console.error('批量更新状态失败:', error)
    toast.error(error.message || '批量更新失败')
  }
}

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

<template>
  <BasicPage
    title="存储管理"
    description="管理系统的存储配置，支持本地、S3、WebDAV、FTP、SFTP等存储方式"
    sticky
  >
    <template #actions>
      <UiButton @click="goToCreate">
        <Plus class="mr-2 h-4 w-4" />
        添加存储
      </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">
              存储配置总数
            </UiCardTitle>
            <Database class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ storageConfigs.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">
              已启用
            </UiCardTitle>
            <CheckCircle class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ activeCount }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              已禁用
            </UiCardTitle>
            <XCircle class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ inactiveCount }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              启用率
            </UiCardTitle>
            <Percent class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ storageConfigs.length ? Math.round(activeCount / storageConfigs.length * 100) : 0 }}%
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            ref="tableRef"
            :loading="loading"
            :data="storageConfigs"
            :on-toggle-status="toggleStatus"
            :on-set-default="setDefault"
            :on-edit="goToEdit"
            :on-delete="confirmDelete"
            @refresh="fetchStorageConfigs"
            @batch-enable="batchToggleStatus(tableRef?.table?.getSelectedRowModel().rows.filter((r: any) => r.original.status === 'inactive').map((r: any) => r.original.id) || [], 'active')"
            @batch-disable="batchToggleStatus(tableRef?.table?.getSelectedRowModel().rows.filter((r: any) => r.original.status === 'active').map((r: any) => r.original.id) || [], 'inactive')"
            @batch-delete="confirmBatchDelete(tableRef?.table?.getSelectedRowModel().rows.map((r: any) => r.original.id) || [])"
          />
        </UiCardContent>
      </UiCard>
    </div>

    <ConfirmDialog
      v-model:open="deleteDialogOpen"
      destructive
      confirm-button-text="删除"
      cancel-button-text="取消"
      @confirm="handleDelete"
    >
      <template #title>
        删除存储配置
      </template>
      <template #description>
        确定要删除存储配置"{{ deleteTarget?.name }}"吗？此操作不可撤销。
      </template>
    </ConfirmDialog>

    <ConfirmDialog
      v-model:open="batchDeleteDialogOpen"
      destructive
      confirm-button-text="删除"
      cancel-button-text="取消"
      @confirm="handleBatchDelete"
    >
      <template #title>
        批量删除存储配置
      </template>
      <template #description>
        确定要删除选中的 {{ batchDeleteIds.length }} 个存储配置吗？此操作不可撤销。
      </template>
    </ConfirmDialog>
  </BasicPage>
</template>
