/*
 *  ParamsPanel.tsx
 *  Zyquo Cloud Web
 *
 *  Author: Simon-Pierre Boucher
 *  Mail: contact@spboucher.ai
 *
 *  Per-conversation parameter editor. Only shows controls the active model's
 *  ParameterSupport allows; every control is gated by an enable checkbox —
 *  unchecked means "provider default" and the key is omitted from requests
 *  entirely (native behavior).
 */

import { findModel } from '../features/catalogHelpers'
import { useStore } from '../state/store'
import type { ChatParameters, Conversation } from '../types'

export default function ParamsPanel({
  conversation,
  onClose,
}: {
  conversation: Conversation
  onClose: () => void
}) {
  const updateConversation = useStore((s) => s.updateConversation)
  const model = findModel(conversation.provider, conversation.modelID)
  const support = model?.parameterSupport
  const params = conversation.parameters

  const patch = (p: Partial<ChatParameters>) => {
    const merged = { ...params, ...p }
    for (const key of Object.keys(merged) as (keyof ChatParameters)[]) {
      if (merged[key] === undefined) delete merged[key]
    }
    updateConversation(conversation.id, { parameters: merged })
  }

  const slider = (
    label: string,
    key: 'temperature' | 'topP' | 'frequencyPenalty' | 'presencePenalty',
    min: number,
    max: number,
    step: number,
    fallback: number
  ) => (
    <div className="settings-row" key={key}>
      <label style={{ display: 'flex', alignItems: 'center', gap: 6, width: 150 }}>
        <input
          type="checkbox"
          checked={params[key] !== undefined}
          onChange={(e) => patch({ [key]: e.target.checked ? fallback : undefined })}
        />
        {label}
      </label>
      {params[key] !== undefined ? (
        <>
          <input
            type="range"
            min={min}
            max={max}
            step={step}
            value={params[key]}
            style={{ flex: 1, accentColor: 'var(--z-accent)' }}
            onChange={(e) => patch({ [key]: Number(e.target.value) })}
          />
          <span style={{ width: 40, textAlign: 'right', fontSize: 12 }}>
            {params[key]?.toFixed(2)}
          </span>
        </>
      ) : (
        <span className="settings-note" style={{ marginLeft: 'auto' }}>
          default
        </span>
      )}
    </div>
  )

  return (
    <div className="overlay" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
      <div className="panel" style={{ width: 420 }}>
        <div className="settings-content">
          <h3>Parameters — {model?.displayName ?? conversation.modelID}</h3>
          {support?.temperature && slider('Temperature', 'temperature', 0, 2, 0.05, 1)}
          {support?.topP && slider('Top P', 'topP', 0, 1, 0.01, 1)}
          {support?.frequencyPenalty &&
            slider('Frequency penalty', 'frequencyPenalty', -2, 2, 0.1, 0)}
          {support?.presencePenalty && slider('Presence penalty', 'presencePenalty', -2, 2, 0.1, 0)}
          <div className="settings-row">
            <span style={{ width: 150 }}>Max tokens</span>
            <input
              className="number-input"
              type="number"
              min={1}
              placeholder="default"
              style={{ width: 100 }}
              value={params.maxTokens ?? ''}
              onChange={(e) =>
                patch({ maxTokens: e.target.value === '' ? undefined : Number(e.target.value) })
              }
            />
          </div>
          {support?.reasoningEffort && (
            <div className="settings-row">
              <span style={{ width: 150 }}>Reasoning effort</span>
              <select
                className="select"
                value={params.reasoningEffort ?? ''}
                onChange={(e) =>
                  patch({
                    reasoningEffort:
                      e.target.value === ''
                        ? undefined
                        : (e.target.value as 'low' | 'medium' | 'high'),
                  })
                }
              >
                <option value="">Default</option>
                <option value="low">Low</option>
                <option value="medium">Medium</option>
                <option value="high">High</option>
              </select>
            </div>
          )}
          {support?.thinkingToggle && (
            <div className="settings-row">
              <label style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <input
                  type="checkbox"
                  checked={params.thinkingEnabled ?? false}
                  onChange={(e) =>
                    patch({ thinkingEnabled: e.target.checked ? true : undefined })
                  }
                />
                Extended thinking
              </label>
            </div>
          )}
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 12 }}>
            <button className="button" onClick={onClose}>
              Done
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}
