<script setup lang="ts">
import { AlertCircle, CheckCircle, Clock, MessageSquare, 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 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 { Ticket } from './tickets/data/schema'

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

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

const loading = ref(true)
const tickets = ref<Ticket[]>([])
const tableRef = ref()

const statusFilter = ref<string>('')
const priorityFilter = ref<string>('')
const typeFilter = 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<Ticket | null>(null)
const batchDeleteDialogOpen = ref(false)
const batchDeleteIds = ref<(string | number)[]>([])

const filteredTickets = computed(() => {
  let result = [...tickets.value]

  if (statusFilter.value) {
    result = result.filter(t => t.status === statusFilter.value)
  }

  if (priorityFilter.value) {
    result = result.filter(t => t.priority === priorityFilter.value)
  }

  if (typeFilter.value) {
    result = result.filter(t => t.type === typeFilter.value)
  }

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

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

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

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

  return result
})

const openCount = computed(() => tickets.value.filter(t => t.status === 'open').length)
const pendingCount = computed(() => tickets.value.filter(t => t.status === 'processing').length)
const resolvedCount = computed(() => tickets.value.filter(t => t.status === 'resolved').length)

const statusOptions = computed(() => [
  { label: t('admin.tickets.status.open'), value: 'open' },
  { label: t('admin.tickets.status.processing'), value: 'processing' },
  { label: t('admin.tickets.status.resolved'), value: 'resolved' },
  { label: t('admin.tickets.status.closed'), value: 'closed' },
])

const priorityOptions = computed(() => [
  { label: t('admin.tickets.priority.low'), value: 'low' },
  { label: t('admin.tickets.priority.normal'), value: 'normal' },
  { label: t('admin.tickets.priority.high'), value: 'high' },
  { label: t('admin.tickets.priority.urgent'), value: 'urgent' },
])

const typeOptions = computed(() => [
  { label: t('admin.tickets.create.ticketTypeSystem'), value: 'system' },
  { label: t('admin.tickets.create.ticketTypeApplication'), value: 'application' },
])

async function fetchTickets() {
  loading.value = true
  try {
    const data = await api.get<{ tickets: Ticket[] }>('/dev/tickets')
    tickets.value = data?.tickets || []
  }
  catch (error) {
    console.error('获取工单列表失败:', error)
    tickets.value = []
  }
  finally {
    loading.value = false
  }
}

async function updateTicketStatus(ticket: Ticket, newStatus: string) {
  try {
    await api.put(`/dev/tickets/${ticket.id}/status`, { status: newStatus })
    fetchTickets()
  }
  catch (error) {
    console.error('更新工单状态失败:', error)
  }
}

function openCreatePage() {
  router.push('/admin/tickets/create')
}

function openTicketDetail(ticket: Ticket) {
  router.push(`/admin/tickets/${ticket.id}`)
}

function confirmDeleteTicket(ticket: Ticket) {
  deleteTarget.value = ticket
  deleteDialogOpen.value = true
}

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

  try {
    await api.delete(`/dev/tickets/${deleteTarget.value.id}`)
    toast.success(t('admin.tickets.deleteSuccess'))
    fetchTickets()
  }
  catch (error: any) {
    console.error('删除工单失败:', error)
    toast.error(error.message || t('admin.tickets.deleteFailed'))
  }
  finally {
    deleteTarget.value = null
  }
}

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

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

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

<template>
  <BasicPage
    :title="t('admin.tickets.title')"
    :description="t('admin.tickets.description')"
    sticky
  >
    <template #actions>
      <UiButton size="sm" @click="openCreatePage">
        <Plus class="mr-2 h-4 w-4" />
        {{ t('admin.tickets.createTicket') }}
      </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.tickets.openCount') }}
            </UiCardTitle>
            <AlertCircle class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ openCount }}
            </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.tickets.pendingCount') }}
            </UiCardTitle>
            <Clock class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ pendingCount }}
            </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.tickets.resolvedCount') }}
            </UiCardTitle>
            <CheckCircle class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ resolvedCount }}
            </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.tickets.totalTickets') }}
            </UiCardTitle>
            <MessageSquare class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ filteredTickets.length }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            ref="tableRef"
            :loading
            :data="filteredTickets"
            :on-update-status="updateTicketStatus"
            :on-view-detail="openTicketDetail"
            :on-delete="confirmDeleteTicket"
            @refresh="fetchTickets"
            @batch-delete="confirmBatchDelete(tableRef?.table?.getSelectedRowModel().rows.map((r: any) => r.original.id) || [])"
          >
            <template #filters>
              <SingleFilter
                v-model="statusFilter"
                :title="t('admin.tickets.columns.status')"
                :options="statusOptions"
              />
              <SingleFilter
                v-model="priorityFilter"
                :title="t('admin.tickets.columns.priority')"
                :options="priorityOptions"
              />
              <SingleFilter
                v-model="typeFilter"
                :title="t('admin.tickets.columns.ticketType')"
                :options="typeOptions"
              />
              <DateRangeFilter
                v-model:start-model-value="createdStartDate"
                v-model:end-model-value="createdEndDate"
                :title="t('admin.tickets.columns.createdAt')"
              />
              <DateRangeFilter
                v-model:start-model-value="updatedStartDate"
                v-model:end-model-value="updatedEndDate"
                :title="t('admin.tickets.columns.updatedAt')"
              />
            </template>
          </DataTable>
        </UiCardContent>
      </UiCard>
    </div>

    <ConfirmDialog
      v-model:open="deleteDialogOpen"
      destructive
      :confirm-button-text="t('admin.tickets.actions.delete')"
      :cancel-button-text="t('admin.tickets.create.cancel')"
      @confirm="handleDeleteTicket"
    >
      <template #title>
        {{ t('admin.tickets.deleteTicket') }}
      </template>
      <template #description>
        {{ t('admin.tickets.deleteTicketConfirm', { title: deleteTarget?.title }) }}
      </template>
    </ConfirmDialog>

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