import type { AppConfig } from "@qjclaw/shared-types"
import { StatusChip } from "../../components/ui/StatusChip"

type SetDraft = (value: string) => void

interface SettingsDrafts {
  lobsterKey: string
  xhsFeishuAppId: string
  xhsFeishuAppSecret: string
  xhsFeishuAppToken: string
  xhsFeishuTableId: string
  copywritingModelApiKey: string
  imageModelApiKey: string
  videoModelApiKey: string
  digitalHumanVolcAccessKey: string
  digitalHumanVolcSecretKey: string
  digitalHumanQiniuAccessKey: string
  digitalHumanQiniuSecretKey: string
  videoAnalyzerBaseUrl: string
  videoAnalyzerModelId: string
  videoAnalyzerApiKey: string
  replicationBriefBaseUrl: string
  replicationBriefModelId: string
  replicationBriefApiKey: string
  vectcutBaseUrl: string
  vectcutFileBaseUrl: string
  vectcutApiKey: string
}

interface SettingsDraftSetters {
  setLobsterKey: SetDraft
  setXhsFeishuAppId: SetDraft
  setXhsFeishuAppSecret: SetDraft
  setXhsFeishuAppToken: SetDraft
  setXhsFeishuTableId: SetDraft
  setCopywritingModelApiKey: SetDraft
  setImageModelApiKey: SetDraft
  setVideoModelApiKey: SetDraft
  setDigitalHumanVolcAccessKey: SetDraft
  setDigitalHumanVolcSecretKey: SetDraft
  setDigitalHumanQiniuAccessKey: SetDraft
  setDigitalHumanQiniuSecretKey: SetDraft
  setVideoAnalyzerBaseUrl: SetDraft
  setVideoAnalyzerModelId: SetDraft
  setVideoAnalyzerApiKey: SetDraft
  setReplicationBriefBaseUrl: SetDraft
  setReplicationBriefModelId: SetDraft
  setReplicationBriefApiKey: SetDraft
  setVectcutBaseUrl: SetDraft
  setVectcutFileBaseUrl: SetDraft
  setVectcutApiKey: SetDraft
}

interface SettingsPanelsProps {
  config: AppConfig | null
  workspaceApiKeyConfigured: boolean
  displayedWorkspacePath: string
  hasPendingWorkspacePathChange: boolean
  hasPendingLobsterKey: boolean
  hasPendingXhsFeishuConfig: boolean
  hasPendingModelKeys: boolean
  saving: boolean
  labels: {
    saving: string
    save: string
    export: string
  }
  drafts: SettingsDrafts
  setters: SettingsDraftSetters
  saveConfig: (options?: { lobsterKey?: string }) => void | Promise<void>
  saveWorkspaceDirectory: () => void | Promise<void>
  restoreWorkspaceDirectory: () => void
  pickWorkspaceDirectory: () => void | Promise<void>
  exportDiagnostics: () => void | Promise<void>
}

export function SettingsPanels({
  config,
  workspaceApiKeyConfigured,
  displayedWorkspacePath,
  hasPendingWorkspacePathChange,
  hasPendingLobsterKey,
  hasPendingXhsFeishuConfig,
  hasPendingModelKeys,
  saving,
  labels,
  drafts,
  setters,
  saveConfig,
  saveWorkspaceDirectory,
  restoreWorkspaceDirectory,
  pickWorkspaceDirectory,
  exportDiagnostics
}: SettingsPanelsProps) {
  const xhsFeishuConfigured = Boolean(
    config?.xhsFeishuConfig.appIdConfigured
    && config?.xhsFeishuConfig.appSecretConfigured
    && config?.xhsFeishuConfig.appTokenConfigured
    && config?.xhsFeishuConfig.tableIdConfigured
  )
  const digitalHumanConfigured = Boolean(
    config?.expertModelConfig.digitalHuman.volcAccessKeyConfigured
    && config?.expertModelConfig.digitalHuman.volcSecretKeyConfigured
    && config?.expertModelConfig.digitalHuman.qiniuAccessKeyConfigured
    && config?.expertModelConfig.digitalHuman.qiniuSecretKeyConfigured
  )

  return (
    <>
      <section className="panel settings-panel settings-panel-modern settings-panel-basic-config">
        <div className="settings-section-card settings-section-card-compact settings-basic-config-card">
          <div className="settings-section-headline settings-section-headline-basic">
            <span className="settings-section-kicker">基础配置</span>
          </div>
          <div className="settings-basic-config-form">
            <div className="settings-basic-config-row">
              <label className="settings-input-label">
                <span className="settings-input-label-text">龙虾密钥</span>
                <input
                  className="settings-truncated-input"
                  type="password"
                  value={drafts.lobsterKey}
                  title={drafts.lobsterKey || undefined}
                  placeholder={workspaceApiKeyConfigured ? "输入新的龙虾密钥或更新绑定" : "请输入龙虾密钥"}
                  onChange={(event) => setters.setLobsterKey(event.target.value)}
                />
              </label>
              <button className="settings-primary-button settings-inline-save-button" disabled={saving || !hasPendingLobsterKey} onClick={() => void saveConfig({ lobsterKey: drafts.lobsterKey })}>{saving ? labels.saving : "保存"}</button>
            </div>
            <div className="settings-basic-config-row settings-basic-config-row-directory">
              <div className="settings-input-label settings-directory-label">
                <span className="settings-input-label-text">工作目录</span>
                <div className="workspace-directory-card settings-basic-directory-card">
                  <div className="workspace-directory-panel settings-basic-directory-panel">
                    <strong className="workspace-directory-path" title={displayedWorkspacePath}>{displayedWorkspacePath}</strong>
                  </div>
                  {hasPendingWorkspacePathChange ? (
                    <div className="workspace-directory-draft-row">
                      <span className="workspace-directory-draft-badge">待保存</span>
                      <div className="workspace-directory-inline-actions">
                        <button disabled={saving} onClick={() => void saveWorkspaceDirectory()}>{saving ? labels.saving : labels.save}</button>
                        <button className="secondary workspace-directory-inline-button" disabled={saving} onClick={restoreWorkspaceDirectory}>恢复当前</button>
                      </div>
                    </div>
                  ) : null}
                </div>
              </div>
              <div className="button-row settings-actions workspace-directory-actions settings-basic-directory-actions">
                <button className="settings-primary-button" disabled={saving || !config} onClick={() => void pickWorkspaceDirectory()}>更改目录</button>
                <button className="secondary" disabled={saving} onClick={() => void exportDiagnostics()}>{labels.export}</button>
              </div>
            </div>
          </div>
        </div>
      </section>
      <section className="panel settings-panel settings-panel-secondary settings-panel-xhs-feishu">
        <div className="settings-section-card settings-section-card-compact">
          <div className="settings-section-headline">
            <div>
              <span className="settings-section-kicker">小红书飞书配置</span>
            </div>
            <StatusChip tone={xhsFeishuConfigured ? "positive" : "warning"}>{xhsFeishuConfigured ? "已配置" : "未配置"}</StatusChip>
          </div>
          <div className="settings-field-grid settings-field-grid-xhs-feishu">
            <label className="settings-input-label">
              <span className="settings-input-label-text">FEISHU_APP_ID</span>
              <input type="password" value={drafts.xhsFeishuAppId} placeholder={config?.xhsFeishuConfig.appIdConfigured ? "留空则保持当前已保存密钥" : "请输入 App ID"} onChange={(event) => setters.setXhsFeishuAppId(event.target.value)} />
            </label>
            <label className="settings-input-label">
              <span className="settings-input-label-text">FEISHU_APP_SECRET</span>
              <input type="password" value={drafts.xhsFeishuAppSecret} placeholder={config?.xhsFeishuConfig.appSecretConfigured ? "留空则保持当前已保存密钥" : "请输入 App Secret"} onChange={(event) => setters.setXhsFeishuAppSecret(event.target.value)} />
            </label>
            <label className="settings-input-label">
              <span className="settings-input-label-text">FEISHU_APP_TOKEN</span>
              <input type="password" value={drafts.xhsFeishuAppToken} placeholder={config?.xhsFeishuConfig.appTokenConfigured ? "留空则保持当前已保存密钥" : "请输入 App Token"} onChange={(event) => setters.setXhsFeishuAppToken(event.target.value)} />
            </label>
            <label className="settings-input-label">
              <span className="settings-input-label-text">FEISHU_TABLE_ID</span>
              <input type="password" value={drafts.xhsFeishuTableId} placeholder={config?.xhsFeishuConfig.tableIdConfigured ? "留空则保持当前已保存密钥" : "请输入 Table ID"} onChange={(event) => setters.setXhsFeishuTableId(event.target.value)} />
            </label>
          </div>
          <div className="button-row settings-actions">
            <button className="settings-primary-button" disabled={saving || !hasPendingXhsFeishuConfig} onClick={() => void saveConfig()}>{saving ? labels.saving : "保存"}</button>
          </div>
        </div>
      </section>
      <section className="panel settings-panel settings-panel-models">
        <div className="settings-section-card settings-section-card-models">
          <div className="settings-section-headline settings-section-headline-minimal">
            <span className="settings-section-kicker">专家模型配置</span>
          </div>
          <div className="model-config-grid model-config-grid-four">
            <article className="model-config-card model-config-card-copywriting">
              <div className="model-config-card-head">
                <div>
                  <strong>文案模型</strong>
                  <p>用于标题、脚本、口播稿与内容润色</p>
                </div>
                <StatusChip tone={config?.expertModelConfig.copywriting.apiKeyConfigured ? "positive" : "warning"}>{config?.expertModelConfig.copywriting.apiKeyConfigured ? "已配置" : "未配置"}</StatusChip>
              </div>
              <div className="model-config-card-body">
                <div className="settings-field-grid single">
                  <label className="settings-input-label">
                    <input type="password" value={drafts.copywritingModelApiKey} placeholder={config?.expertModelConfig.copywriting.apiKeyConfigured ? "留空则保持当前已保存密钥" : "请输入文案模型 API Key"} onChange={(event) => setters.setCopywritingModelApiKey(event.target.value)} />
                  </label>
                </div>
              </div>
            </article>
            <article className="model-config-card model-config-card-image">
              <div className="model-config-card-head">
                <div>
                  <strong>生图模型</strong>
                  <p>用于封面草图、画面创意和视觉素材生成</p>
                </div>
                <StatusChip tone={config?.expertModelConfig.image.apiKeyConfigured ? "positive" : "warning"}>{config?.expertModelConfig.image.apiKeyConfigured ? "已配置" : "未配置"}</StatusChip>
              </div>
              <div className="model-config-card-body">
                <div className="settings-field-grid single">
                  <label className="settings-input-label">
                    <input type="password" value={drafts.imageModelApiKey} placeholder={config?.expertModelConfig.image.apiKeyConfigured ? "留空则保持当前已保存密钥" : "请输入生图模型 API Key"} onChange={(event) => setters.setImageModelApiKey(event.target.value)} />
                  </label>
                </div>
              </div>
            </article>
            <article className="model-config-card model-config-card-video">
              <div className="model-config-card-head">
                <div>
                  <strong>普通视频模型</strong>
                  <p>用于纯画面视频生成</p>
                </div>
                <StatusChip tone={config?.expertModelConfig.video.apiKeyConfigured ? "positive" : "warning"}>{config?.expertModelConfig.video.apiKeyConfigured ? "已配置" : "未配置"}</StatusChip>
              </div>
              <div className="model-config-card-body">
                <div className="settings-field-grid single">
                  <label className="settings-input-label">
                    <input type="password" value={drafts.videoModelApiKey} placeholder={config?.expertModelConfig.video.apiKeyConfigured ? "留空则保持当前已保存密钥" : "请输入视频模型 API Key"} onChange={(event) => setters.setVideoModelApiKey(event.target.value)} />
                  </label>
                </div>
              </div>
            </article>
            <article className="model-config-card model-config-card-digital-human">
              <div className="model-config-card-head">
                <div>
                  <strong>数字人配置</strong>
                  <p>用于数字人口播视频，火山与七牛的四个 Key</p>
                </div>
                <StatusChip tone={digitalHumanConfigured ? "positive" : "warning"}>{digitalHumanConfigured ? "已配置" : "未配置"}</StatusChip>
              </div>
              <div className="model-config-card-body model-config-card-body-digital-human">
                <div className="settings-field-grid settings-field-grid-digital-human">
                  <label className="settings-input-label">
                    <span className="settings-input-label-text">VOLC_ACCESS_KEY</span>
                    <input type="password" value={drafts.digitalHumanVolcAccessKey} placeholder={config?.expertModelConfig.digitalHuman.volcAccessKeyConfigured ? "留空则保持当前已保存密钥" : "请输入火山 ACCESS_KEY"} onChange={(event) => setters.setDigitalHumanVolcAccessKey(event.target.value)} />
                  </label>
                  <label className="settings-input-label">
                    <span className="settings-input-label-text">VOLC_SECRET_KEY</span>
                    <input type="password" value={drafts.digitalHumanVolcSecretKey} placeholder={config?.expertModelConfig.digitalHuman.volcSecretKeyConfigured ? "留空则保持当前已保存密钥" : "请输入火山 SECRET_KEY"} onChange={(event) => setters.setDigitalHumanVolcSecretKey(event.target.value)} />
                  </label>
                  <label className="settings-input-label">
                    <span className="settings-input-label-text">QINIU_ACCESS_KEY</span>
                    <input type="password" value={drafts.digitalHumanQiniuAccessKey} placeholder={config?.expertModelConfig.digitalHuman.qiniuAccessKeyConfigured ? "留空则保持当前已保存密钥" : "请输入七牛 ACCESS_KEY"} onChange={(event) => setters.setDigitalHumanQiniuAccessKey(event.target.value)} />
                  </label>
                  <label className="settings-input-label">
                    <span className="settings-input-label-text">QINIU_SECRET_KEY</span>
                    <input type="password" value={drafts.digitalHumanQiniuSecretKey} placeholder={config?.expertModelConfig.digitalHuman.qiniuSecretKeyConfigured ? "留空则保持当前已保存密钥" : "请输入七牛 SECRET_KEY"} onChange={(event) => setters.setDigitalHumanQiniuSecretKey(event.target.value)} />
                  </label>
                </div>
              </div>
            </article>
            <article className="model-config-card model-config-card-video-analyzer">
              <div className="model-config-card-head">
                <div>
                  <strong>Video Analyzer</strong>
                  <p>用于抖音样本分析阶段。</p>
                </div>
                <StatusChip tone={config?.douyinRuntimeConfig.videoAnalyzer.apiKeyConfigured ? "positive" : "warning"}>{config?.douyinRuntimeConfig.videoAnalyzer.apiKeyConfigured ? "已配置" : "未配置"}</StatusChip>
              </div>
              <div className="model-config-card-body">
                <div className="settings-field-grid">
                  <label className="settings-input-label">
                    <span className="settings-input-label-text">base_url</span>
                    <input value={drafts.videoAnalyzerBaseUrl} placeholder="https://ark.cn-beijing.volces.com/api/v3" onChange={(event) => setters.setVideoAnalyzerBaseUrl(event.target.value)} />
                  </label>
                  <label className="settings-input-label">
                    <span className="settings-input-label-text">model_id</span>
                    <input value={drafts.videoAnalyzerModelId} placeholder="doubao-vision" onChange={(event) => setters.setVideoAnalyzerModelId(event.target.value)} />
                  </label>
                  <label className="settings-input-label">
                    <span className="settings-input-label-text">api_key</span>
                    <input type="password" value={drafts.videoAnalyzerApiKey} placeholder={config?.douyinRuntimeConfig.videoAnalyzer.apiKeyConfigured ? "留空则保持当前已保存密钥" : "请输入 Video Analyzer API Key"} onChange={(event) => setters.setVideoAnalyzerApiKey(event.target.value)} />
                  </label>
                </div>
              </div>
            </article>
            <article className="model-config-card model-config-card-replication-brief">
              <div className="model-config-card-head">
                <div>
                  <strong>Replication Brief</strong>
                  <p>用于抖音 brief 生成阶段。</p>
                </div>
                <StatusChip tone={config?.douyinRuntimeConfig.replicationBrief.apiKeyConfigured ? "positive" : "warning"}>{config?.douyinRuntimeConfig.replicationBrief.apiKeyConfigured ? "已配置" : "未配置"}</StatusChip>
              </div>
              <div className="model-config-card-body">
                <div className="settings-field-grid">
                  <label className="settings-input-label">
                    <span className="settings-input-label-text">base_url</span>
                    <input value={drafts.replicationBriefBaseUrl} placeholder="https://dashscope.aliyuncs.com/compatible-mode/v1" onChange={(event) => setters.setReplicationBriefBaseUrl(event.target.value)} />
                  </label>
                  <label className="settings-input-label">
                    <span className="settings-input-label-text">model_id</span>
                    <input value={drafts.replicationBriefModelId} placeholder="qwen-max" onChange={(event) => setters.setReplicationBriefModelId(event.target.value)} />
                  </label>
                  <label className="settings-input-label">
                    <span className="settings-input-label-text">api_key</span>
                    <input type="password" value={drafts.replicationBriefApiKey} placeholder={config?.douyinRuntimeConfig.replicationBrief.apiKeyConfigured ? "留空则保持当前已保存密钥" : "请输入 Replication Brief API Key"} onChange={(event) => setters.setReplicationBriefApiKey(event.target.value)} />
                  </label>
                </div>
              </div>
            </article>
            <article className="model-config-card model-config-card-vectcut">
              <div className="model-config-card-head">
                <div>
                  <strong>VectCut</strong>
                  <p>用于抖音后处理剪辑阶段。</p>
                </div>
                <StatusChip tone={config?.douyinRuntimeConfig.vectcut.apiKeyConfigured ? "positive" : "warning"}>{config?.douyinRuntimeConfig.vectcut.apiKeyConfigured ? "已配置" : "未配置"}</StatusChip>
              </div>
              <div className="model-config-card-body">
                <div className="settings-field-grid">
                  <label className="settings-input-label">
                    <span className="settings-input-label-text">base_url</span>
                    <input value={drafts.vectcutBaseUrl} placeholder="https://open.vectcut.com/cut_jianying" onChange={(event) => setters.setVectcutBaseUrl(event.target.value)} />
                  </label>
                  <label className="settings-input-label">
                    <span className="settings-input-label-text">file_base_url</span>
                    <input value={drafts.vectcutFileBaseUrl} placeholder="https://open.vectcut.com" onChange={(event) => setters.setVectcutFileBaseUrl(event.target.value)} />
                  </label>
                  <label className="settings-input-label">
                    <span className="settings-input-label-text">api_key</span>
                    <input type="password" value={drafts.vectcutApiKey} placeholder={config?.douyinRuntimeConfig.vectcut.apiKeyConfigured ? "留空则保持当前已保存密钥" : "请输入 VectCut API Key"} onChange={(event) => setters.setVectcutApiKey(event.target.value)} />
                  </label>
                </div>
              </div>
            </article>
          </div>
          <div className="button-row settings-actions">
            <button className="settings-primary-button" disabled={saving || !hasPendingModelKeys} onClick={() => void saveConfig()}>{saving ? labels.saving : "保存模型配置"}</button>
          </div>
        </div>
      </section>
    </>
  )
}
