import { useEffect, useState } from 'react'
import { Modal } from './Modal'
import { apiInjectActiveModels, apiInjectStatus } from '../ipc'
import type { ApiStatus, LaunchOptions, ModelInfo } from '../types'

interface Props {
  onLaunch: (opts: LaunchOptions) => void
  onClose: () => void
}

/** 把启动选项转换为 claude 命令行参数 */
export function buildClaudeArgs(opts: LaunchOptions): string[] {
  const args: string[] = []
  if (opts.model) args.push('--model', opts.model)
  if (opts.permissionMode) args.push('--permission-mode', opts.permissionMode)
  if (opts.extraArgs.trim()) {
    args.push(...opts.extraArgs.trim().split(/\s+/))
  }
  return args
}

export function NewSessionDialog({ onLaunch, onClose }: Props) {
  const [model, setModel] = useState('')
  const [customModel, setCustomModel] = useState('')
  const [permissionMode, setPermissionMode] = useState<LaunchOptions['permissionMode']>('')
  const [extraArgs, setExtraArgs] = useState('')
  /** 注入态：official 时保持官方硬编码清单；direct/router 用注入接口/路由聚合清单 */
  const [apiStatus, setApiStatus] = useState<ApiStatus | null>(null)
  const [remoteModels, setRemoteModels] = useState<ModelInfo[] | null>(null)

  useEffect(() => {
    void (async () => {
      try {
        const s = await apiInjectStatus()
        setApiStatus(s)
        if (s.mode !== 'official') {
          setRemoteModels(await apiInjectActiveModels())
        }
      } catch {
        // 清单拉取失败：静默退回（仅默认项 + 自定义）
      }
    })()
  }, [])

  const submit = () => {
    onLaunch({
      model: model === 'custom' ? customModel.trim() : model,
      permissionMode,
      extraArgs
    })
  }

  const mode = apiStatus?.mode ?? 'official'
  const modeHint =
    mode === 'router'
      ? '路由模式：清单为多模型路由的全量对外模型（可选任意接口的模型启动）'
      : mode === 'direct'
        ? '直连模式：清单来自当前注入接口'
        : ''

  return (
    <Modal
      title="新建会话"
      onClose={onClose}
      footer={
        <>
          <button className="btn" onClick={onClose}>
            取消
          </button>
          <button className="btn primary" onClick={submit}>
            启动
          </button>
        </>
      }
    >
      <label className="label">模型</label>
      <select className="select" style={{ width: '100%' }} value={model} onChange={(e) => setModel(e.target.value)}>
        {mode === 'official' ? (
          <>
            <option value="">默认</option>
            <option value="sonnet">sonnet</option>
            <option value="opus">opus</option>
            <option value="haiku">haiku</option>
            <option value="custom">自定义…</option>
          </>
        ) : (
          <>
            <option value="">
              默认{apiStatus?.model ? `（${apiStatus.model}）` : '（注入模型）'}
            </option>
            {(remoteModels ?? []).map((m) => (
              <option key={m.id} value={m.id}>
                {m.displayName}
              </option>
            ))}
            <option value="custom">自定义…</option>
          </>
        )}
      </select>
      {modeHint && (
        <div style={{ marginTop: 4, fontSize: 11, color: 'var(--text-faint)' }}>{modeHint}</div>
      )}
      {mode !== 'official' && remoteModels === null && (
        <div style={{ marginTop: 4, fontSize: 11, color: 'var(--text-faint)' }}>
          清单加载中或失败时可直接选「自定义…」手输模型名
        </div>
      )}
      {model === 'custom' && (
        <input
          className="input"
          style={{ width: '100%', marginTop: 6 }}
          placeholder="模型名称或完整模型 ID"
          value={customModel}
          onChange={(e) => setCustomModel(e.target.value)}
        />
      )}

      <label className="label">权限模式</label>
      <select
        className="select"
        style={{ width: '100%' }}
        value={permissionMode}
        onChange={(e) => setPermissionMode(e.target.value as LaunchOptions['permissionMode'])}
      >
        <option value="">默认（逐项确认）</option>
        <option value="plan">plan（先出计划）</option>
        <option value="acceptEdits">acceptEdits（自动接受编辑）</option>
        <option value="bypassPermissions">bypassPermissions（跳过权限确认）</option>
      </select>

      <label className="label">附加参数（可选，按空格分隔）</label>
      <input
        className="input"
        style={{ width: '100%' }}
        placeholder="例如 --verbose"
        value={extraArgs}
        onChange={(e) => setExtraArgs(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === 'Enter') submit()
        }}
      />
    </Modal>
  )
}

interface ResumeProps {
  title: string
  onResume: (permissionMode: LaunchOptions['permissionMode']) => void
  onClose: () => void
}

/**
 * 恢复会话对话框：选择本次恢复使用的权限模式。
 * Claude Code 不会保存/恢复上次的权限模式，且 bypass 只有在启动时带
 * --permission-mode 等标志才会进入 Shift+Tab 循环，故恢复时需在此显式选择。
 */
export function ResumeSessionDialog({ title, onResume, onClose }: ResumeProps) {
  const [permissionMode, setPermissionMode] = useState<LaunchOptions['permissionMode']>('')

  return (
    <Modal
      title="恢复会话"
      onClose={onClose}
      footer={
        <>
          <button className="btn" onClick={onClose}>
            取消
          </button>
          <button className="btn primary" onClick={() => onResume(permissionMode)}>
            恢复
          </button>
        </>
      }
    >
      <div className="label" style={{ marginTop: 0 }}>
        会话「{title}」
      </div>

      <label className="label">权限模式</label>
      <select
        className="select"
        style={{ width: '100%' }}
        value={permissionMode}
        onChange={(e) => setPermissionMode(e.target.value as LaunchOptions['permissionMode'])}
      >
        <option value="">默认（逐项确认）</option>
        <option value="plan">plan（先出计划）</option>
        <option value="acceptEdits">acceptEdits（自动接受编辑）</option>
        <option value="bypassPermissions">bypassPermissions（跳过权限确认）</option>
      </select>
      <div style={{ marginTop: 6, fontSize: 11, color: 'var(--text-faint)' }}>
        选 bypassPermissions 即一恢复就跳过权限确认；选其它项后仍可在终端里按 Shift+Tab 切换。
      </div>
    </Modal>
  )
}
