import { ref, computed } from 'vue'
import { http } from '@/api'
import { useSnackbar } from '@/composables/useSnackbar'
import type { PaginatedResponse, PushItem } from '@/types/api'
import type { usePushForm } from './usePushForm'
import type { usePushServers } from './usePushServers'
import type { DiagnoseResult } from './types'

type PushForm = ReturnType<typeof usePushForm>
type PushServers = ReturnType<typeof usePushServers>

const LOG_STATUS_OPTIONS = [
  { label: '成功', value: 'success' },
  { label: '失败', value: 'failed' },
  { label: '进行中', value: 'running' },
  { label: '已取消', value: 'cancelled' },
]

const LOG_SYNC_MODE_OPTIONS = [
  { label: '增量', value: 'incremental' },
  { label: '全量', value: 'full' },
  { label: '校验和', value: 'checksum' },
]

const LOG_HEADERS = [
  { title: '时间', key: 'started_at', width: 170 },
  { title: '服务器', key: 'server_name', width: 120 },
  { title: '状态', key: 'status', width: 88 },
  { title: '模式', key: 'sync_mode', width: 88 },
  { title: '源路径', key: 'source_path' },
  { title: '目标路径', key: 'target_path' },
  { title: '错误', key: 'error_message', width: 200 },
  { title: '操作', key: 'actions', width: 88, sortable: false },
]

export function usePushLogs(form: PushForm, servers: PushServers) {
  const snackbar = useSnackbar()

  const logs = ref<PushItem[]>([])
  const logTotal = ref(0)
  const logLoading = ref(false)
  const logPage = ref(1)
  const logStatusFilter = ref<string | null>(null)
  const logSyncModeFilter = ref<string | null>(null)
  const logServerFilter = ref<number | null>(null)
  const reconcilingLogs = ref(false)

  const showDiagnose = ref(false)
  const diagnoseLoading = ref(false)
  const diagnoseResult = ref<DiagnoseResult | null>(null)
  const diagnoseTarget = ref<PushItem | null>(null)

  const logServerOptions = computed(() =>
    servers.servers.value.map(s => ({ title: s.name, value: s.id })),
  )

  function onLogFilterChange() {
    logPage.value = 1
    loadLogs()
  }

  async function loadLogs() {
    logLoading.value = true
    try {
      const params: Record<string, string | number> = {
        page: logPage.value,
        per_page: 15,
      }
      if (logStatusFilter.value) params.status = logStatusFilter.value
      if (logSyncModeFilter.value) params.sync_mode = logSyncModeFilter.value
      if (logServerFilter.value != null) params.server_id = logServerFilter.value

      const res = await http.get<PaginatedResponse<PushItem>>('/servers/logs', params)
      logs.value = res.items || []
      logTotal.value = res.total || 0
    } catch {
      logs.value = []
      logTotal.value = 0
    } finally {
      logLoading.value = false
    }
  }

  async function reconcileStaleLogs() {
    reconcilingLogs.value = true
    try {
      const res = await http.post<{ reconciled: number; max_age_minutes: number }>(
        '/sync/reconcile-stale-logs',
        { max_age_minutes: 120 },
      )
      const n = res.reconciled ?? 0
      snackbar(n > 0 ? `已订正 ${n} 条卡住的推送记录` : '没有需要订正的记录')
      await loadLogs()
    } catch (e: unknown) {
      snackbar(e instanceof Error ? e.message : '订正失败', 'error')
    } finally {
      reconcilingLogs.value = false
    }
  }

  async function openDiagnose(item: PushItem) {
    diagnoseTarget.value = item
    diagnoseResult.value = null
    showDiagnose.value = true
    diagnoseLoading.value = true
    try {
      diagnoseResult.value = await http.post<DiagnoseResult>('/sync/diagnose', {
        server_id: item.server_id,
        target_path: item.target_path || form.targetPath.value || undefined,
      })
    } catch (e: unknown) {
      snackbar(e instanceof Error ? e.message : '诊断失败', 'error')
      showDiagnose.value = false
    } finally {
      diagnoseLoading.value = false
    }
  }

  function closeDiagnose() {
    showDiagnose.value = false
  }

  return {
    logs,
    logTotal,
    logLoading,
    logPage,
    logStatusFilter,
    logSyncModeFilter,
    logServerFilter,
    reconcilingLogs,
    logStatusOptions: LOG_STATUS_OPTIONS,
    logSyncModeOptions: LOG_SYNC_MODE_OPTIONS,
    logHeaders: LOG_HEADERS,
    logServerOptions,
    showDiagnose,
    diagnoseLoading,
    diagnoseResult,
    diagnoseTarget,
    onLogFilterChange,
    loadLogs,
    reconcileStaleLogs,
    openDiagnose,
    closeDiagnose,
  }
}
