import type { DimSdkStore } from '#cli/core/store'
import type { ComputedRef, Ref } from 'vue'
import { t } from '#cli/i18n'
import { resolveUserPath } from '@simon_he/vue-tui'
import { computed, ref } from 'vue'
import { dialogSize } from '../../ui/utils/dialog-sizes'
import { getProcessCwd } from './runtime'

export function usePathPicker(
  opts: Readonly<{
    store: DimSdkStore
    cols: ComputedRef<number>
    rows: ComputedRef<number>
    nodeLike: boolean
  }>,
): Readonly<{
  showPathPicker: Ref<boolean>
  pathPickerMode: Ref<'directory' | 'file'>
  pathPickerQuery: Ref<string>
  pathPickerError: Ref<string | null>
  pickerWorkspace: ComputedRef<string>
  pickerW: ComputedRef<number>
  pickerH: ComputedRef<number>
  pathPickerTitle: ComputedRef<string>
  pathPickerPlaceholder: ComputedRef<string>
  openPathPicker: (mode: 'directory' | 'file', query?: string) => void
  closePathPicker: () => void
}> {
  const showPathPicker = ref(false)
  const pathPickerMode = ref<'directory' | 'file'>('directory')
  const pathPickerQuery = ref('')
  const pathPickerError = ref<string | null>(null)

  const pickerWorkspace = computed(() => {
    const cwd = String(opts.store.state.context?.cwd ?? '.')
    if (!opts.nodeLike) return cwd
    return resolveUserPath(getProcessCwd(), cwd)
  })

  const pathPickerTitle = computed(() =>
    pathPickerMode.value === 'directory'
      ? t('pathPicker.titleWorkspace')
      : t('pathPicker.titleFile'),
  )
  const pathPickerPlaceholder = computed(() =>
    pathPickerMode.value === 'directory'
      ? t('pathPicker.placeholderWorkspace')
      : t('pathPicker.placeholderFile'),
  )

  const pickerSize = computed(() =>
    dialogSize('lg', opts.cols.value, opts.rows.value),
  )
  const pickerW = computed(() => pickerSize.value.w)
  const pickerH = computed(() => pickerSize.value.h)

  function openPathPicker(mode: 'directory' | 'file', query = ''): void {
    if (!opts.nodeLike) {
      pathPickerError.value = 'node-only'
      return
    }
    showPathPicker.value = true
    pathPickerMode.value = mode
    pathPickerQuery.value = String(query ?? '')
    pathPickerError.value = null
  }

  function closePathPicker(): void {
    showPathPicker.value = false
    pathPickerQuery.value = ''
    pathPickerError.value = null
  }

  return {
    showPathPicker,
    pathPickerMode,
    pathPickerQuery,
    pathPickerError,
    pickerWorkspace,
    pickerW,
    pickerH,
    pathPickerTitle,
    pathPickerPlaceholder,
    openPathPicker,
    closePathPicker,
  }
}
