<script setup lang="ts">
import { Ban, CheckCircle, Code, Link, Plus } 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 type { DynamicCode } from '@/pages/admin/dynamic-code/data/schema'

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 DataTable from '@/pages/admin/dynamic-code/components/data-table.vue'
import api from '@/services/api'

const { t } = useI18n()

interface Application {
  id: number
  name: string
}

const router = useRouter()

const loading = ref(true)
const codes = ref<DynamicCode[]>([])
const tableRef = ref()
const applications = ref<Application[]>([])

const appFilter = ref<string>('')
const statusFilter = ref<string>('')
const createdStartDate = ref<string>('')
const createdEndDate = ref<string>('')
const updatedStartDate = ref<string>('')
const updatedEndDate = ref<string>('')

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

const filteredCodes = computed(() => {
  let result = codes.value

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

  if (statusFilter.value) {
    if (statusFilter.value === 'enabled') {
      result = result.filter(code => code.enabled === true)
    }
    else if (statusFilter.value === 'disabled') {
      result = result.filter(code => code.enabled === false)
    }
  }

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

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

  if (updatedStartDate.value) {
    const fromDateTime = updatedStartDate.value.includes('T')
      ? updatedStartDate.value.replace('T', ' ')
      : `${updatedStartDate.value} 00:00`
    result = result.filter(code => code.updated_at >= fromDateTime)
  }

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

  return result
})

const enabledCount = computed(() => filteredCodes.value.filter(code => code.enabled === true).length)
const disabledCount = computed(() => filteredCodes.value.filter(code => code.enabled === false).length)
const linkedAppsCount = computed(() => new Set(filteredCodes.value.map(code => code.application_id)).size)

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

const statusOptions = computed(() => [
  { label: t('admin.cloudFunction.enabled'), value: 'enabled' },
  { label: t('admin.cloudFunction.disabled'), value: 'disabled' },
])

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

async function fetchCodes() {
  loading.value = true
  try {
    const data = await api.get<DynamicCode[]>('/dev/dynamic-codes')
    codes.value = Array.isArray(data) ? data : []
  }
  catch (error) {
    console.error('获取云端函数列表失败:', error)
    codes.value = []
  }
  finally {
    loading.value = false
  }
}

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

async function toggleStatus(code: DynamicCode) {
  try {
    const newStatus = !code.enabled
    await api.put(`/dev/dynamic-codes/${code.id}/status`, { enabled: newStatus })
    toast.success(t('admin.cloudFunction.statusUpdateSuccess'))
    fetchCodes()
  }
  catch (error: any) {
    console.error('切换云端函数状态失败:', error)
    toast.error(error.message || t('admin.cloudFunction.statusUpdateFailed'))
  }
}

function editCode(code: DynamicCode) {
  router.push(`/admin/cloud-function/${code.id}`)
}

function confirmDeleteCode(code: DynamicCode) {
  deleteTarget.value = code
  deleteDialogOpen.value = true
}

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

  try {
    await api.delete(`/dev/dynamic-codes/${deleteTarget.value.id}`)
    toast.success(t('admin.cloudFunction.deleteSuccess'))
    fetchCodes()
  }
  catch (error: any) {
    console.error('删除云端函数失败:', error)
    toast.error(error.message || t('admin.cloudFunction.deleteFailed'))
  }
  finally {
    deleteTarget.value = null
  }
}

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

async function handleBatchDelete() {
  try {
    await api.delete('/dev/dynamic-codes/batch', { ids: batchDeleteIds.value } as any)
    toast.success(t('admin.cloudFunction.deleteSuccess'))
    fetchCodes()
  }
  catch (error: any) {
    console.error('批量删除失败:', error)
    toast.error(error.message || t('admin.cloudFunction.deleteFailed'))
  }
  finally {
    batchDeleteIds.value = []
  }
}

async function batchToggleStatus(ids: (string | number)[], enabled: boolean) {
  try {
    await api.put('/dev/dynamic-codes/batch/status', { ids, enabled })
    toast.success(t('admin.cloudFunction.batchUpdateSuccess'))
    fetchCodes()
  }
  catch (error: any) {
    console.error('批量更新状态失败:', error)
    toast.error(error.message || t('admin.cloudFunction.batchUpdateFailed'))
  }
}

onMounted(() => {
  fetchApplications()
  fetchCodes()
})
</script>

<template>
  <BasicPage
    :title="t('admin.cloudFunction.title')"
    :description="t('admin.cloudFunction.description')"
    sticky
  >
    <template #actions>
      <UiButton size="sm" @click="goToCreate">
        <Plus class="mr-2 h-4 w-4" />
        {{ t('admin.cloudFunction.createBtn') }}
      </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.cloudFunction.totalCodes') }}
            </UiCardTitle>
            <Code class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ filteredCodes.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.cloudFunction.enabled') }}
            </UiCardTitle>
            <CheckCircle class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ enabledCount }}
            </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.cloudFunction.disabled') }}
            </UiCardTitle>
            <Ban class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ disabledCount }}
            </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.cloudFunction.linkedApps') }}
            </UiCardTitle>
            <Link class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ linkedAppsCount }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            ref="tableRef"
            :loading
            :data="filteredCodes"
            :on-toggle-status="toggleStatus"
            :on-edit="editCode"
            :on-delete="confirmDeleteCode"
            @refresh="fetchCodes"
            @batch-enable="batchToggleStatus(tableRef?.table?.getSelectedRowModel().rows.map((r: any) => r.original.id) || [], true)"
            @batch-disable="batchToggleStatus(tableRef?.table?.getSelectedRowModel().rows.map((r: any) => r.original.id) || [], false)"
            @batch-delete="confirmBatchDelete(tableRef?.table?.getSelectedRowModel().rows.map((r: any) => r.original.id) || [])"
          >
            <template #filters>
              <SingleFilter
                v-model="appFilter"
                :title="t('admin.cloudFunction.application')"
                :options="applicationOptions"
              />
              <SingleFilter
                v-model="statusFilter"
                :title="t('admin.cloudFunction.status')"
                :options="statusOptions"
              />
              <DateRangeFilter
                v-model:start-model-value="createdStartDate"
                v-model:end-model-value="createdEndDate"
                :title="t('admin.cloudFunction.columns.createdAt')"
              />
              <DateRangeFilter
                v-model:start-model-value="updatedStartDate"
                v-model:end-model-value="updatedEndDate"
                :title="t('admin.cloudFunction.columns.updatedAt')"
              />
            </template>
          </DataTable>
        </UiCardContent>
      </UiCard>
    </div>

    <ConfirmDialog
      v-model:open="deleteDialogOpen"
      destructive
      :confirm-button-text="t('admin.cloudFunction.delete')"
      :cancel-button-text="t('admin.cloudFunction.create.cancelBtn')"
      @confirm="handleDeleteCode"
    >
      <template #title>
        {{ t('admin.cloudFunction.deleteCode') }}
      </template>
      <template #description>
        {{ t('admin.cloudFunction.deleteCodeConfirm', { codeName: deleteTarget?.name }) }}
      </template>
    </ConfirmDialog>

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