import { useMeshStore } from '../stores/meshStore';
import { MATCAP_NAMES } from '../utils/generateMatcap';
import type { RenderMode } from './Toolbar';

const sectionStyle: React.CSSProperties = {
  marginBottom: 8, paddingBottom: 8, borderBottom: '1px solid #444',
};
const labelStyle: React.CSSProperties = {
  display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4, fontSize: 11, color: '#ccc',
};
const sliderStyle: React.CSSProperties = {
  width: '100%', accentColor: '#4a90d9',
};

const MODES: { mode: RenderMode | 'matcap'; label: string }[] = [
  { mode: 'solid', label: 'Solid' },
  { mode: 'flat', label: 'Flat' },
  { mode: 'wireframe', label: 'Wire' },
  { mode: 'points', label: 'Points' },
  { mode: 'matcap', label: 'Matcap' },
];

export function RenderSettingsPanel() {
  const { state, dispatch } = useMeshStore();
  const set = (key: string, value: unknown) => dispatch({ type: 'SET_RENDER_SETTING', key, value });

  return (
    <div
      data-testid="render-settings-panel"
      style={{
        position: 'absolute', top: 38, right: 48, zIndex: 60,
        background: '#2d2d2d', border: '1px solid #444', borderRadius: 6,
        padding: 12, width: 240, fontSize: 11, fontFamily: 'monospace', color: '#ccc',
        maxHeight: '80vh', overflowY: 'auto',
      }}
    >
      {/* Shading */}
      <div style={sectionStyle}>
        <div style={{ fontWeight: 'bold', marginBottom: 6 }}>Shading</div>
        <div style={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}>
          {MODES.map(({ mode, label }) => (
            <button
              key={mode}
              data-testid={`mode-${mode}`}
              onClick={() => dispatch({ type: 'SET_RENDER_MODE', mode: mode === 'matcap' ? 'solid' : mode as RenderMode })}
              style={{
                padding: '2px 6px', border: '1px solid #555', borderRadius: 2, fontSize: 10,
                background: (mode === 'matcap' ? state.globalRenderMode === 'solid' && state.matcapType !== '' : state.globalRenderMode === mode) ? '#4a90d9' : '#333',
                color: '#ccc', cursor: 'pointer',
              }}
            >
              {label}
            </button>
          ))}
        </div>
        <label style={{ ...labelStyle, marginTop: 6 }}>
          Matcap:
          <select
            data-testid="matcap-select"
            value={state.matcapType}
            onChange={(e) => set('matcapType', e.target.value)}
            style={{ flex: 1, background: '#1e1e1e', color: '#ccc', border: '1px solid #444', borderRadius: 2, fontSize: 10, padding: '1px 2px' }}
          >
            <option value="">None</option>
            {MATCAP_NAMES.map((n) => <option key={n} value={n}>{n}</option>)}
          </select>
        </label>
      </div>

      {/* Lighting */}
      <div style={sectionStyle}>
        <div style={{ fontWeight: 'bold', marginBottom: 6 }}>Lighting</div>
        <label style={labelStyle}>
          <input type="checkbox" data-testid="toggle-ssao" checked={state.ssaoEnabled}
            onChange={(e) => set('ssaoEnabled', e.target.checked)} />
          SSAO
        </label>
        <label style={labelStyle}>
          <input type="checkbox" data-testid="toggle-shadows" checked={state.shadowsEnabled}
            onChange={(e) => set('shadowsEnabled', e.target.checked)} />
          Shadows
        </label>
        <label style={labelStyle}>
          Intensity:
          <input type="range" min="0" max="2" step="0.1" value={state.lightIntensity}
            onChange={(e) => set('lightIntensity', parseFloat(e.target.value))}
            style={sliderStyle} />
          {state.lightIntensity.toFixed(1)}
        </label>
      </div>

      {/* Display */}
      <div style={sectionStyle}>
        <div style={{ fontWeight: 'bold', marginBottom: 6 }}>Display</div>
        <label style={labelStyle}>
          <input type="checkbox" checked={state.showGrid}
            onChange={() => dispatch({ type: 'TOGGLE_GRID' })} />
          Grid
        </label>
        <label style={labelStyle}>
          <input type="checkbox" checked={state.showBBox}
            onChange={() => dispatch({ type: 'TOGGLE_BBOX' })} />
          Bounding Box
        </label>
        <label style={labelStyle}>
          <input type="checkbox" data-testid="toggle-edges" checked={state.edgesEnabled}
            onChange={(e) => set('edgesEnabled', e.target.checked)} />
          Crease Edges
        </label>
        {state.edgesEnabled && (
          <label style={labelStyle}>
            Angle:
            <input type="range" data-testid="edge-angle" min="0" max="180" step="1" value={state.edgeAngle}
              onChange={(e) => set('edgeAngle', parseInt(e.target.value))}
              style={sliderStyle} />
            {state.edgeAngle}&deg;
          </label>
        )}
      </div>

      {/* Clipping */}
      <div style={{ marginBottom: 0 }}>
        <div style={{ fontWeight: 'bold', marginBottom: 6 }}>Clipping Plane</div>
        <label style={labelStyle}>
          <input type="checkbox" data-testid="toggle-clipping" checked={state.clippingEnabled}
            onChange={(e) => set('clippingEnabled', e.target.checked)} />
          Enabled
        </label>
        {state.clippingEnabled && (
          <>
            <div style={{ display: 'flex', gap: 4, marginBottom: 4 }}>
              {(['X', 'Y', 'Z'] as const).map((axis) => (
                <button
                  key={axis}
                  data-testid={`clip-axis-${axis}`}
                  onClick={() => set('clippingAxis', axis)}
                  style={{
                    padding: '2px 8px', border: '1px solid #555', borderRadius: 2,
                    background: state.clippingAxis === axis ? '#4a90d9' : '#333',
                    color: '#ccc', cursor: 'pointer', fontSize: 10,
                  }}
                >
                  {axis}
                </button>
              ))}
              <button
                onClick={() => set('clippingFlipped', !state.clippingFlipped)}
                style={{ padding: '2px 6px', border: '1px solid #555', borderRadius: 2, background: '#333', color: '#ccc', cursor: 'pointer', fontSize: 10 }}
              >
                {state.clippingFlipped ? 'Flip ←' : 'Flip →'}
              </button>
            </div>
            <label style={labelStyle}>
              Position:
              <input type="range" data-testid="clip-position" min="0" max="100" step="1" value={state.clippingPosition}
                onChange={(e) => set('clippingPosition', parseInt(e.target.value))}
                style={sliderStyle} />
              {state.clippingPosition}%
            </label>
          </>
        )}
      </div>
    </div>
  );
}
