<script setup lang="ts">
import { Database, LayoutGrid, Link, Plus, Unlink } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import ConfirmDialog from '@/components/confirm-dialog.vue'
import DateRangeFilter from '@/components/data-table/date-range-filter.vue'
import SingleFilter from '@/components/data-table/single-filter.vue'
import { BasicPage } from '@/components/global-layout'
import api from '@/services/api'

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

import DataTable from './components/data-table.vue'

const { t } = useI18n()
const router = useRouter()

interface Application {
  id: number
  name: string
  app_key: string
}

const loading = ref(true)
const constants = ref<CloudConstant[]>([])
const applications = ref<Application[]>([])

const appFilter = ref<string>('')
const startDate = ref<string>('')
const endDate = ref<string>('')

const deleteDialogOpen = ref(false)
const deleteTarget = ref<CloudConstant | null>(null)
const batchDialogOpen = ref(false)
const batchAction = ref<'enable' | 'disable' | 'delete' | null>(null)
const selectedRows = ref<CloudConstant[]>([])

const filteredConstants = computed(() => {
  let result = [...constants.value]

  if (appFilter.value) {
    result = result.filter(c => String(c.app_id) === appFilter.value)
  }

  if (startDate.value) {
    const fromDateTime = startDate.value.includes('T')
      ? startDate.value.replace('T', ' ')
      : `${startDate.value} 00:00`
    result = result.filter(c => c.created_at >= fromDateTime)
  }

  if (endDate.value) {
    const toDateTime = endDate.value.includes('T')
      ? endDate.value.replace('T', ' ')
      : `${endDate.value} 23:59`
    result = result.filter(c => c.created_at <= toDateTime)
  }

  return result
})

const linkedCount = computed(() => constants.value.filter(c => c.app_id).length)
const unlinkedCount = computed(() => constants.value.filter(c => !c.app_id).length)

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

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

async function fetchConstants() {
  loading.value = true
  try {
    const data = await api.get<{ constants: CloudConstant[] }>('/dev/cloud-constants')
    const consts = data?.constants || []
    constants.value = consts.map((c: any) => ({
      ...c,
      application_name: applications.value.find(app => app.id === c.app_id)?.name || '',
    }))
  }
  catch (error) {
    console.error('获取云端常量失败:', error)
    constants.value = []
  }
  finally {
    loading.value = false
  }
}

function openCreatePage() {
  router.push('/admin/cloud-constants/create')
}

function openEditPage(constant: CloudConstant) {
  router.push(`/admin/cloud-constants/${constant.id}`)
}

function confirmDelete(constant: CloudConstant) {
  deleteTarget.value = constant
  deleteDialogOpen.value = true
}

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

  try {
    await api.delete(`/dev/cloud-constants/${deleteTarget.value.id}`)
    toast.success(t('admin.cloudConstants.deleteSuccess'))
    fetchConstants()
  }
  catch (error: any) {
    console.error('删除云端常量失败:', error)
    toast.error(error.message || t('admin.cloudConstants.deleteFailed'))
  }
  finally {
    deleteTarget.value = null
  }
}

async function handleToggleStatus(constant: CloudConstant) {
  const newStatus = constant.status === 'active' ? 'inactive' : 'active'
  try {
    await api.put(`/dev/cloud-constants/${constant.id}`, {
      key: constant.key,
      value: constant.value,
      var_type: constant.var_type,
      description: constant.description,
      status: newStatus,
    })
    toast.success(newStatus === 'active' ? t('admin.cloudConstants.enableSuccess') : t('admin.cloudConstants.disableSuccess'))
    fetchConstants()
  }
  catch (error: any) {
    console.error('更新状态失败:', error)
    toast.error(error.message || t('admin.cloudConstants.updateFailed'))
  }
}

function handleDownload(constant: CloudConstant) {
  if (constant.var_type !== 'binary')
    return
  const token = localStorage.getItem('token')
  const url = `/api/v1/dev/cloud-constants/${constant.id}/download?token=${token}`
  window.open(url, '_blank')
}

function openBatchDialog(action: 'enable' | 'disable' | 'delete', rows: CloudConstant[]) {
  batchAction.value = action
  selectedRows.value = rows
  batchDialogOpen.value = true
}

async function handleBatchAction() {
  if (!batchAction.value || selectedRows.value.length === 0)
    return

  const ids = selectedRows.value.map(c => c.id)
  try {
    if (batchAction.value === 'delete') {
      await Promise.all(ids.map(id => api.delete(`/dev/cloud-constants/${id}`)))
      toast.success(t('admin.cloudConstants.batchDeleteSuccess'))
    }
    else {
      const status = batchAction.value === 'enable' ? 'active' : 'inactive'
      await Promise.all(selectedRows.value.map(c => api.put(`/dev/cloud-constants/${c.id}`, {
        key: c.key,
        value: c.value,
        var_type: c.var_type,
        description: c.description,
        status,
      })))
      toast.success(batchAction.value === 'enable' ? t('admin.cloudConstants.batchEnableSuccess') : t('admin.cloudConstants.batchDisableSuccess'))
    }
    fetchConstants()
  }
  catch (error: any) {
    console.error('批量操作失败:', error)
    toast.error(error.message || t('admin.cloudConstants.batchFailed'))
  }
  finally {
    batchAction.value = null
    selectedRows.value = []
  }
}

onMounted(async () => {
  await fetchApplications()
  fetchConstants()
})
</script>

<template>
  <BasicPage
    :title="t('admin.cloudConstants.title')"
    :description="t('admin.cloudConstants.description')"
    sticky
  >
    <template #actions>
      <UiButton size="sm" @click="openCreatePage">
        <Plus class="mr-2 h-4 w-4" />
        {{ t('admin.cloudConstants.addConstant') }}
      </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.cloudConstants.totalConstants') }}
            </UiCardTitle>
            <Database class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ filteredConstants.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.cloudConstants.linkedApps') }}
            </UiCardTitle>
            <Link class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ linkedCount }}
            </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.cloudConstants.unlinked') }}
            </UiCardTitle>
            <Unlink class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ unlinkedCount }}
            </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.cloudConstants.appCount') }}
            </UiCardTitle>
            <LayoutGrid class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ applications.length }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            :loading
            :data="filteredConstants"
            :on-edit="openEditPage"
            :on-delete="confirmDelete"
            :on-toggle-status="handleToggleStatus"
            :on-download="handleDownload"
            @refresh="fetchConstants"
            @batch-action="openBatchDialog"
          >
            <template #filters>
              <SingleFilter
                v-model="appFilter"
                :title="t('admin.cloudConstants.application')"
                :options="applicationOptions"
              />
              <DateRangeFilter
                v-model:start-model-value="startDate"
                v-model:end-model-value="endDate"
              />
            </template>
          </DataTable>
        </UiCardContent>
      </UiCard>
    </div>

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

    <ConfirmDialog
      v-model:open="batchDialogOpen"
      :destructive="batchAction === 'delete'"
      :confirm-button-text="batchAction === 'delete' ? t('admin.cloudConstants.delete') : t('common.confirm')"
      :cancel-button-text="t('common.cancel')"
      @confirm="handleBatchAction"
    >
      <template #title>
        {{ batchAction === 'delete' ? t('admin.cloudConstants.batchDelete') : batchAction === 'enable' ? t('admin.cloudConstants.batchEnable') : t('admin.cloudConstants.batchDisable') }}
      </template>
      <template #description>
        {{ batchAction === 'delete' ? t('admin.cloudConstants.batchDeleteConfirm', { count: selectedRows.length }) : batchAction === 'enable' ? t('admin.cloudConstants.batchEnableConfirm', { count: selectedRows.length }) : t('admin.cloudConstants.batchDisableConfirm', { count: selectedRows.length }) }}
      </template>
    </ConfirmDialog>
  </BasicPage>
</template>
