import { Button, Drawer, Empty, InputNumber, Slider } from 'antd';
import type { Agent, ModelOverrides } from '../../../api';
import McpResourcesDrawer from '../../../components/McpResourcesDrawer';
import SessionSidebar from '../../../components/SessionSidebar';
import PromptLibraryPage from '../../PromptLibraryPage';

export default function ChatDrawers(props: {
  agentId?: string;
  agent: Agent | null;
  input: string;
  setInput: (updater: (prev: string) => string) => void;
  overrides: ModelOverrides;
  setOverrides: (updater: (prev: ModelOverrides) => ModelOverrides) => void;
  sessionId: string | null;
  setSessionId: (v: string | null) => void;
  setHighlightId: (v: string | null) => void;
  sessionRefresh: number;
  mcpDrawerOpen: boolean;
  setMcpDrawerOpen: (v: boolean) => void;
  tplDrawerOpen: boolean;
  setTplDrawerOpen: (v: boolean) => void;
  paramsDrawerOpen: boolean;
  setParamsDrawerOpen: (v: boolean) => void;
  historyDrawerOpen: boolean;
  setHistoryDrawerOpen: (v: boolean) => void;
  notify: { success: (t: string) => void };
}) {
  const {
    agentId,
    agent,
    setInput,
    overrides,
    setOverrides,
    sessionId,
    setSessionId,
    setHighlightId,
    sessionRefresh,
    mcpDrawerOpen,
    setMcpDrawerOpen,
    tplDrawerOpen,
    setTplDrawerOpen,
    paramsDrawerOpen,
    setParamsDrawerOpen,
    historyDrawerOpen,
    setHistoryDrawerOpen,
    notify
  } = props;

  return (
    <>
      {agentId && (
        <McpResourcesDrawer
          agentId={agentId}
          open={mcpDrawerOpen}
          onClose={() => setMcpDrawerOpen(false)}
          onUse={(text) => setInput((cur) => cur + text)}
        />
      )}

      <Drawer title="📚 选择 Prompt 模板" open={tplDrawerOpen} onClose={() => setTplDrawerOpen(false)} width={520}>
        <PromptLibraryPage
          onSelect={(t) => {
            setInput((cur) => (cur ? cur + '\n\n' : '') + t.body);
            setTplDrawerOpen(false);
            notify.success('已插入到输入框');
          }}
        />
      </Drawer>

      <Drawer title="⚙️ 模型参数（仅本会话临时生效）" open={paramsDrawerOpen} onClose={() => setParamsDrawerOpen(false)} width={380}>
        <div
          style={{
            marginBottom: 16,
            padding: 12,
            background: 'var(--color-warning-soft)',
            borderRadius: 10,
            fontSize: 12,
            color: 'var(--color-warning)',
            border: '1px solid var(--color-border)'
          }}
        >
          💡 这里设置的参数会临时覆盖智能体的默认配置，<b>仅作用于当前浏览器会话</b>，不会写回到智能体本身。
          <br />
          关闭页面或清空字段即可恢复默认。
        </div>

        <div style={{ marginBottom: 24 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
            <span>🌡 Temperature（创造性）</span>
            <span style={{ fontSize: 12, color: 'var(--color-text-secondary)' }}>默认：{agent?.temperature ?? 0.7}</span>
          </div>
          <Slider
            min={0}
            max={2}
            step={0.05}
            value={overrides.temperature ?? agent?.temperature ?? 0.7}
            onChange={(v) => setOverrides((o) => ({ ...o, temperature: v as number }))}
            marks={{ 0: '严谨', 0.7: '默认', 1.4: '发散', 2: '混沌' }}
          />
          {overrides.temperature !== undefined && (
            <Button size="small" type="link" style={{ padding: 0 }} onClick={() => setOverrides((o) => ({ ...o, temperature: undefined }))}>
              ↺ 恢复默认
            </Button>
          )}
        </div>

        <div style={{ marginBottom: 24 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
            <span>🎯 Top P（核采样）</span>
            <span style={{ fontSize: 12, color: 'var(--color-text-secondary)' }}>未设置时跟随模型默认</span>
          </div>
          <Slider min={0.1} max={1} step={0.05} value={overrides.topP ?? 1} onChange={(v) => setOverrides((o) => ({ ...o, topP: v as number }))} disabled={overrides.topP === undefined} />
          {overrides.topP === undefined ? (
            <Button size="small" type="link" style={{ padding: 0 }} onClick={() => setOverrides((o) => ({ ...o, topP: 1 }))}>
              ✚ 启用 Top P
            </Button>
          ) : (
            <Button size="small" type="link" style={{ padding: 0 }} onClick={() => setOverrides((o) => ({ ...o, topP: undefined }))}>
              ↺ 取消
            </Button>
          )}
        </div>

        <div style={{ marginBottom: 24 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
            <span>📏 Max Tokens（生成长度上限）</span>
            <span style={{ fontSize: 12, color: 'var(--color-text-secondary)' }}>未设置时由模型决定</span>
          </div>
          <InputNumber
            value={overrides.maxTokens}
            onChange={(v) => setOverrides((o) => ({ ...o, maxTokens: v == null ? undefined : Number(v) }))}
            min={1}
            max={16384}
            placeholder="例如 2048"
            style={{ width: '100%' }}
          />
        </div>

        <Button block onClick={() => setOverrides(() => ({}))}>
          🔄 全部恢复默认
        </Button>
      </Drawer>

      <Drawer
        title="历史对话"
        placement="right"
        width={320}
        onClose={() => setHistoryDrawerOpen(false)}
        open={historyDrawerOpen}
        styles={{ body: { padding: 0 } }}
      >
        {agentId ? (
          <SessionSidebar
            agentId={agentId}
            activeSessionId={sessionId}
            onChange={(sid, opts) => {
              setSessionId(sid);
              setHighlightId(opts?.highlightMessageId || null);
              setHistoryDrawerOpen(false);
            }}
            refreshTick={sessionRefresh}
          />
        ) : (
          <Empty description="未选择 Agent" />
        )}
      </Drawer>
    </>
  );
}
