"use client";

export interface SessionInfoData {
  sessionId: string | null;
  sessionFile?: string;
  cwd: string | null;
  name?: string;
  model: { provider: string; modelId: string } | null;
  thinkingLevel?: string;
  messageCount: number;
  tokens?: { input: number; output: number; cacheRead: number; cacheWrite: number } | null;
  cost?: number | null;
  contextUsage?: { percent: number | null; contextWindow: number; tokens: number | null } | null;
  autoCompactionEnabled?: boolean;
  autoRetryEnabled?: boolean;
  steeringMode?: string;
  followUpMode?: string;
  toolPreset?: string;
  activeTools?: string[];
}

interface Props {
  open: boolean;
  onClose: () => void;
  info: SessionInfoData;
  onReload?: () => void;
  onExport?: () => void;
  onClone?: () => void;
}

function Row({ label, value, mono }: { label: string; value: React.ReactNode; mono?: boolean }) {
  return (
    <div style={{ display: "flex", gap: 12, padding: "7px 0", borderBottom: "1px solid var(--border)" }}>
      <div style={{ width: 110, flexShrink: 0, fontSize: 11, color: "var(--text-dim)", paddingTop: 1 }}>{label}</div>
      <div
        style={{
          flex: 1,
          minWidth: 0,
          fontSize: 12,
          color: "var(--text)",
          fontFamily: mono ? "var(--font-mono)" : "var(--font-sans)",
          wordBreak: "break-all",
          lineHeight: 1.45,
        }}
      >
        {value ?? <span style={{ color: "var(--text-dim)" }}>—</span>}
      </div>
    </div>
  );
}

export function SessionInfoPanel({ open, onClose, info, onReload, onExport, onClone }: Props) {
  if (!open) return null;

  const totalTokens = info.tokens
    ? info.tokens.input + info.tokens.output + info.tokens.cacheRead + info.tokens.cacheWrite
    : null;

  return (
    <div
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 1100,
        background: "rgba(0,0,0,0.35)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: 16,
      }}
      onClick={onClose}
    >
      <div
        style={{
          width: "100%",
          maxWidth: 480,
          maxHeight: "85vh",
          overflow: "auto",
          background: "var(--bg)",
          border: "1px solid var(--border)",
          borderRadius: 14,
          boxShadow: "0 16px 48px rgba(0,0,0,0.2)",
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            padding: "14px 16px",
            borderBottom: "1px solid var(--border)",
          }}
        >
          <div style={{ fontSize: 14, fontWeight: 600, color: "var(--text)" }}>会话信息</div>
          <button
            type="button"
            onClick={onClose}
            style={{
              border: "none",
              background: "transparent",
              color: "var(--text-dim)",
              cursor: "pointer",
              fontSize: 18,
              lineHeight: 1,
              padding: 4,
            }}
            aria-label="关闭"
          >
            ×
          </button>
        </div>

        <div style={{ padding: "4px 16px 12px" }}>
          <Row label="名称" value={info.name || "（未命名）"} />
          <Row label="Session ID" value={info.sessionId} mono />
          <Row label="文件" value={info.sessionFile} mono />
          <Row label="工作目录" value={info.cwd} mono />
          <Row
            label="模型"
            value={info.model ? `${info.model.provider}/${info.model.modelId}` : null}
            mono
          />
          <Row label="Thinking" value={info.thinkingLevel} />
          <Row label="消息数" value={String(info.messageCount)} />
          <Row
            label="Tokens"
            value={
              info.tokens
                ? `↑${info.tokens.input} ↓${info.tokens.output} R${info.tokens.cacheRead} W${info.tokens.cacheWrite} · Σ${totalTokens}`
                : null
            }
            mono
          />
          <Row
            label="费用"
            value={info.cost != null && info.cost > 0 ? `$${info.cost.toFixed(4)}` : null}
            mono
          />
          <Row
            label="上下文"
            value={
              info.contextUsage
                ? `${info.contextUsage.percent != null ? info.contextUsage.percent.toFixed(1) + "%" : "—"} · ${info.contextUsage.tokens ?? "—"} / ${info.contextUsage.contextWindow}`
                : null
            }
            mono
          />
          <Row label="Auto compact" value={info.autoCompactionEnabled == null ? null : info.autoCompactionEnabled ? "开" : "关"} />
          <Row label="Auto retry" value={info.autoRetryEnabled == null ? null : info.autoRetryEnabled ? "开" : "关"} />
          <Row label="Steer 模式" value={info.steeringMode} />
          <Row label="Follow-up" value={info.followUpMode} />
          <Row label="Tools 预设" value={info.toolPreset} />
          <Row
            label="活动工具"
            value={info.activeTools?.length ? info.activeTools.join(", ") : "（无）"}
            mono
          />
        </div>

        <div
          style={{
            display: "flex",
            gap: 8,
            padding: "12px 16px 16px",
            borderTop: "1px solid var(--border)",
            flexWrap: "wrap",
          }}
        >
          {onReload && (
            <button type="button" className="pi-composer-icon-btn" onClick={onReload} style={{ height: 30, padding: "0 10px" }}>
              重载资源
            </button>
          )}
          {onExport && (
            <button type="button" className="pi-composer-icon-btn" onClick={onExport} style={{ height: 30, padding: "0 10px" }}>
              导出
            </button>
          )}
          {onClone && (
            <button type="button" className="pi-composer-icon-btn" onClick={onClone} style={{ height: 30, padding: "0 10px" }}>
              克隆分支
            </button>
          )}
          <div style={{ flex: 1 }} />
          <button
            type="button"
            onClick={onClose}
            style={{
              height: 30,
              padding: "0 14px",
              borderRadius: 6,
              border: "1px solid var(--border)",
              background: "var(--bg-panel)",
              color: "var(--text)",
              cursor: "pointer",
              fontSize: 12,
            }}
          >
            关闭
          </button>
        </div>
      </div>
    </div>
  );
}
