import { textCellWidth, TText, useTerminal } from '@simon_he/vue-tui'
import { defineComponent, getCurrentInstance, h, inject, watch } from 'vue'
import { readRuntimeVersion } from '#cli/core/version-env'
import { ChatPageContextKey } from '../context'
import { CHAT_HEADER_H } from '../logic/layout'
import { ellipsisByCells } from '../text'

export const DimSdkChatHeader = defineComponent({
  name: 'DimSdkChatHeader',
  setup() {
    const instance = getCurrentInstance()
    const injected = inject(ChatPageContextKey)
    if (!injected) throw new Error('DimSdkChatHeader missing ChatPageContext')
    const ctx = injected
    const { render, scheduler } = useTerminal()

    watch(
      () => [
        ctx.sessionHeaderSummary.value,
        ctx.headerStatsDisplay.value,
        ctx.cols.value,
        ctx.contentW.value,
        Number((ctx as any)?.store?.state?.chromeVersion ?? 0),
      ],
      () => {
        if (instance?.isMounted)
          ;(instance as any)?.update?.()
        render.invalidatePlane('chrome')
        scheduler.invalidate({ priority: 'high', plane: 'chrome' })
      },
      { flush: 'post' },
    )

    return () => {
      const ui = ctx.ui
      const windowBg = ui.style(['bg.window'])
      const muted = ui.style(['text.muted', 'bg.window'])
      const sepStyle = ui.style(['border.default', 'bg.window'])

      const env = (ctx.store.state.context?.env ?? {}) as Record<
        string,
        unknown
      >
      const version = readRuntimeVersion(env)
      const rowW = Math.max(0, ctx.contentW.value - 4)

      const versionTag = version ? `v${version}` : ''
      const statsRaw = String(ctx.headerStatsDisplay.value ?? '').trim()
      const rightRaw = `${statsRaw}${versionTag ? ` | ${versionTag}` : ''}`
      const minSummaryW = 12
      const gap = 2
      const rightMaxW = rightRaw ? Math.max(0, rowW - minSummaryW - gap) : 0
      const right = rightRaw ? ellipsisByCells(rightRaw, rightMaxW) : ''
      const rightW = right ? textCellWidth(right) : 0
      const rightX = right ? Math.max(0, ctx.contentW.value - 2 - rightW) : 0

      const summaryX = 2
      const summaryAvailW = rightW ? Math.max(0, rowW - rightW - gap) : rowW
      const summary = ellipsisByCells(
        ctx.sessionHeaderSummary.value,
        summaryAvailW,
      )

      const headerY = 1
      const sepY = CHAT_HEADER_H
      const headerFill = (() => {
        const w = Math.max(0, ctx.cols.value)
        const h = Math.max(0, CHAT_HEADER_H)
        if (w === 0 || h === 0) return ''
        const line = ' '.repeat(w)
        return Array.from({ length: h }, () => line).join('\n')
      })()

      const nodes = [
        h(TText, {
          key: 'header-bg',
          x: 0,
          y: 0,
          w: ctx.cols.value,
          h: CHAT_HEADER_H,
          value: headerFill,
          style: windowBg,
          zIndex: -30,
        }),
        ctx.cols.value > 0
          ? h(TText, {
              key: 'header-sep',
              x: 0,
              y: sepY,
              w: ctx.cols.value,
              value: '─'.repeat(Math.max(0, ctx.cols.value)),
              style: sepStyle,
              zIndex: -29,
            })
          : null,
      ] as any[]

      if (summaryAvailW > 0) {
        nodes.push(
          h(TText, {
            key: 'header-summary',
            x: summaryX,
            y: headerY,
            w: summaryAvailW,
            value: summary,
            style: muted,
          }),
        )
      }

      if (right) {
        nodes.push(
          h(TText, {
            key: 'header-stats',
            x: rightX,
            y: headerY,
            value: right,
            style: muted,
          }),
        )
      }

      return nodes
    }
  },
})
