import { api } from '../../api/client'
import { registerIslanderActionHandler } from './actionExecutor'

type CopyActionDeps = {
  personaId: string
  missionId?: string
  keywords: string[]
  onStartScan?: () => void
  onGenerateDraft?: (scanPostId: string) => void
  onStartAnalyze?: () => void
  onGenerateMatrix?: () => void
  reload?: () => void
}

let deps: CopyActionDeps | null = null
let handlersRegistered = false

export function bindCopyIslanderActions(next: CopyActionDeps | null) {
  deps = next
}

export function unbindCopyIslanderActions() {
  deps = null
}

export function ensureCopyActionHandlers() {
  if (handlersRegistered) return
  handlersRegistered = true

  registerIslanderActionHandler('startViralScan', async () => {
    if (!deps?.personaId) {
      return { action: { type: 'startViralScan' }, ok: false, detail: '請先選擇人設' }
    }
    try {
      await api.post(
        `/api/v1/personas/${encodeURIComponent(deps.personaId)}/viral-scan-jobs`,
        { keywords: deps.keywords.filter((k) => k.trim()) },
        { auth: true },
      )
      deps.onStartScan?.()
      deps.reload?.()
      return { action: { type: 'startViralScan' }, ok: true, detail: '已啟動爆款海巡背景任務' }
    } catch (e) {
      const message = e instanceof Error ? e.message : '啟動失敗'
      return { action: { type: 'startViralScan' }, ok: false, detail: message }
    }
  })

  registerIslanderActionHandler('startCopyMissionAnalyze', async () => {
    if (!deps?.personaId || !deps.missionId) {
      return { action: { type: 'startCopyMissionAnalyze' }, ok: false, detail: '請先開啟拷貝任務' }
    }
    try {
      await api.post(
        `/api/v1/personas/${encodeURIComponent(deps.personaId)}/copy-missions/${encodeURIComponent(deps.missionId)}/analyze-jobs`,
        {},
        { auth: true },
      )
      deps.onStartAnalyze?.()
      deps.reload?.()
      return { action: { type: 'startCopyMissionAnalyze' }, ok: true, detail: '已啟動研究地圖分析' }
    } catch (e) {
      const message = e instanceof Error ? e.message : '啟動失敗'
      return { action: { type: 'startCopyMissionAnalyze' }, ok: false, detail: message }
    }
  })

  registerIslanderActionHandler('startCopyMissionScan', async () => {
    if (!deps?.personaId || !deps.missionId) {
      return { action: { type: 'startCopyMissionScan' }, ok: false, detail: '請先開啟拷貝任務' }
    }
    try {
      await api.post(
        `/api/v1/personas/${encodeURIComponent(deps.personaId)}/copy-missions/${encodeURIComponent(deps.missionId)}/scan-jobs`,
        {},
        { auth: true },
      )
      deps.onStartScan?.()
      deps.reload?.()
      return { action: { type: 'startCopyMissionScan' }, ok: true, detail: '已啟動拷貝任務海巡' }
    } catch (e) {
      const message = e instanceof Error ? e.message : '啟動失敗'
      return { action: { type: 'startCopyMissionScan' }, ok: false, detail: message }
    }
  })

  registerIslanderActionHandler('generateCopyMatrix', async () => {
    if (!deps?.personaId || !deps.missionId) {
      return { action: { type: 'generateCopyMatrix' }, ok: false, detail: '請先開啟拷貝任務' }
    }
    try {
      await api.post(
        `/api/v1/personas/${encodeURIComponent(deps.personaId)}/copy-missions/${encodeURIComponent(deps.missionId)}/matrix-jobs`,
        { count: 5 },
        { auth: true },
      )
      deps.onGenerateMatrix?.()
      deps.reload?.()
      return { action: { type: 'generateCopyMatrix' }, ok: true, detail: '已啟動內容矩陣背景任務' }
    } catch (e) {
      const message = e instanceof Error ? e.message : '產出失敗'
      return { action: { type: 'generateCopyMatrix' }, ok: false, detail: message }
    }
  })

  registerIslanderActionHandler('publishCopyDraft', async (action) => {
    if (!deps?.personaId) {
      return { action, ok: false, detail: '請先選擇人設' }
    }
    if (action.type !== 'publishCopyDraft') {
      return { action, ok: false, detail: '動作類型錯誤' }
    }
    const draftId = action.draft_id?.trim()
    if (!draftId) {
      return { action, ok: false, detail: '缺少 draft_id' }
    }
    if (!action.confirm) {
      return { action, ok: false, detail: '請設定 confirm=true 後再發布' }
    }
    try {
      await api.post(
        `/api/v1/personas/${encodeURIComponent(deps.personaId)}/copy-drafts/${encodeURIComponent(draftId)}/publish`,
        { confirm: true },
        { auth: true },
      )
      deps.reload?.()
      return { action, ok: true, detail: '已發布仿寫貼文到 Threads' }
    } catch (e) {
      const message = e instanceof Error ? e.message : '發布失敗'
      return { action, ok: false, detail: message }
    }
  })

  registerIslanderActionHandler('generateCopyDraft', async (action) => {
    if (!deps?.personaId) {
      return { action, ok: false, detail: '請先選擇人設' }
    }
    if (action.type !== 'generateCopyDraft') {
      return { action, ok: false, detail: '動作類型錯誤' }
    }
    const scanPostId = action.scan_post_id?.trim()
    if (!scanPostId) {
      return { action, ok: false, detail: '缺少 scan_post_id' }
    }
    if (!deps.missionId) {
      return { action, ok: false, detail: '請先開啟拷貝任務' }
    }
    try {
      await api.post(
        `/api/v1/personas/${encodeURIComponent(deps.personaId)}/copy-missions/${encodeURIComponent(deps.missionId)}/copy-draft-jobs`,
        { scan_post_id: scanPostId },
        { auth: true },
      )
      deps.onGenerateDraft?.(scanPostId)
      deps.reload?.()
      return { action, ok: true, detail: '已啟動深仿寫背景任務' }
    } catch (e) {
      const message = e instanceof Error ? e.message : '產出失敗'
      return { action, ok: false, detail: message }
    }
  })

  registerIslanderActionHandler('navigateToPersona8D', async (_action, ctx: { navigate: (path: string) => void }) => {
    if (!deps?.personaId) {
      return { action: { type: 'navigateToPersona8D' }, ok: false, detail: '請先選擇人設' }
    }
    ctx.navigate(`/personas/${deps.personaId}#style-8d`)
    return { action: { type: 'navigateToPersona8D' }, ok: true, detail: '已前往 8D 對標區塊' }
  })
}

/** @deprecated use bindCopyIslanderActions */
export function setCopyActionDeps(next: CopyActionDeps | null) {
  bindCopyIslanderActions(next)
}

/** @deprecated use ensureCopyActionHandlers */
export function registerCopyIslanderActions() {
  ensureCopyActionHandlers()
}