<script setup lang="ts">
import { Globe, LayoutGrid, Plus, User, Variable } 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 { CloudVariable } 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 variables = ref<CloudVariable[]>([])
const applications = ref<Application[]>([])

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

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

const filteredVariables = computed(() => {
  let result = [...variables.value]

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

  if (scopeFilter.value) {
    result = result.filter(v => v.scope === scopeFilter.value)
  }

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

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

  return result
})

const appScopeCount = computed(() => variables.value.filter(v => v.scope === 'app').length)
const userScopeCount = computed(() => variables.value.filter(v => v.scope === 'user').length)

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

const scopeOptions = computed(() => [
  { label: t('admin.cloudVariables.appScope'), value: 'app' },
  { label: t('admin.cloudVariables.userScope'), value: 'user' },
])

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

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

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

function openEditPage(variable: CloudVariable) {
  router.push(`/admin/cloud-variables/${variable.id}`)
}

function confirmDelete(variable: CloudVariable) {
  deleteTarget.value = variable
  deleteDialogOpen.value = true
}

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

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

async function handleToggleStatus(variable: CloudVariable) {
  const newStatus = variable.status === 'active' ? 'inactive' : 'active'
  try {
    await api.put(`/dev/cloud-variables/${variable.id}`, {
      key: variable.key,
      default_value: variable.default_value,
      var_type: variable.var_type,
      scope: variable.scope,
      write_permission: variable.write_permission,
      description: variable.description,
      status: newStatus,
    })
    toast.success(newStatus === 'active' ? t('admin.cloudVariables.enableSuccess') : t('admin.cloudVariables.disableSuccess'))
    fetchVariables()
  }
  catch (error: any) {
    console.error('更新状态失败:', error)
    toast.error(error.message || t('admin.cloudVariables.updateFailed'))
  }
}

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

function handleViewRecords(variable: CloudVariable) {
  router.push(`/admin/cloud-variables/${variable.id}/records?app_id=${variable.app_id}`)
}

function openBatchDialog(action: 'enable' | 'disable' | 'delete', rows: CloudVariable[]) {
  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(v => v.id)
  try {
    if (batchAction.value === 'delete') {
      await Promise.all(ids.map(id => api.delete(`/dev/cloud-variables/${id}`)))
      toast.success(t('admin.cloudVariables.batchDeleteSuccess'))
    }
    else {
      const status = batchAction.value === 'enable' ? 'active' : 'inactive'
      await Promise.all(selectedRows.value.map(v => api.put(`/dev/cloud-variables/${v.id}`, {
        key: v.key,
        default_value: v.default_value,
        var_type: v.var_type,
        scope: v.scope,
        write_permission: v.write_permission,
        description: v.description,
        status,
      })))
      toast.success(batchAction.value === 'enable' ? t('admin.cloudVariables.batchEnableSuccess') : t('admin.cloudVariables.batchDisableSuccess'))
    }
    fetchVariables()
  }
  catch (error: any) {
    console.error('批量操作失败:', error)
    toast.error(error.message || t('admin.cloudVariables.batchFailed'))
  }
  finally {
    batchAction.value = null
    selectedRows.value = []
  }
}

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

<template>
  <BasicPage
    :title="t('admin.cloudVariables.title')"
    :description="t('admin.cloudVariables.description')"
    sticky
  >
    <template #actions>
      <UiButton size="sm" @click="openCreatePage">
        <Plus class="mr-2 h-4 w-4" />
        {{ t('admin.cloudVariables.addVariable') }}
      </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.cloudVariables.totalVariables') }}
            </UiCardTitle>
            <Variable class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ filteredVariables.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.cloudVariables.appScopeVariables') }}
            </UiCardTitle>
            <Globe class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ appScopeCount }}
            </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.cloudVariables.userScopeVariables') }}
            </UiCardTitle>
            <User class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ userScopeCount }}
            </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.cloudVariables.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="filteredVariables"
            :on-edit="openEditPage"
            :on-delete="confirmDelete"
            :on-toggle-status="handleToggleStatus"
            :on-download="handleDownload"
            :on-view-records="handleViewRecords"
            @refresh="fetchVariables"
            @batch-action="openBatchDialog"
          >
            <template #filters>
              <SingleFilter
                v-model="appFilter"
                :title="t('admin.cloudVariables.application')"
                :options="applicationOptions"
              />
              <SingleFilter
                v-model="scopeFilter"
                :title="t('admin.cloudVariables.scope')"
                :options="scopeOptions"
              />
              <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.cloudVariables.delete')"
      :cancel-button-text="t('common.reset')"
      @confirm="handleDelete"
    >
      <template #title>
        {{ t('admin.cloudVariables.deleteVariable') }}
      </template>
      <template #description>
        {{ t('admin.cloudVariables.deleteConfirm', { key: deleteTarget?.key }) }}
      </template>
    </ConfirmDialog>

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