import { useState, useEffect } from 'react';

interface Prefs {
  defaultBgColor: string;
  defaultMeshColor: string;
  maxUndoHistory: number;
  defaultRenderMode: string;
  defaultSSAO: boolean;
  defaultShadows: boolean;
  defaultBrushSize: number;
  selectionColor: string;
}

const DEFAULT_PREFS: Prefs = {
  defaultBgColor: 'dark',
  defaultMeshColor: '#b0b0b0',
  maxUndoHistory: 20,
  defaultRenderMode: 'solid',
  defaultSSAO: false,
  defaultShadows: false,
  defaultBrushSize: 20,
  selectionColor: '#ff0000',
};

function loadPrefs(): Prefs {
  try {
    const stored = localStorage.getItem('meshlab_prefs');
    if (stored) return { ...DEFAULT_PREFS, ...JSON.parse(stored) };
  } catch { /* ignore */ }
  return { ...DEFAULT_PREFS };
}

function savePrefs(prefs: Prefs) {
  try { localStorage.setItem('meshlab_prefs', JSON.stringify(prefs)); } catch { /* ignore */ }
}

interface Props {
  onClose: () => void;
}

export function PreferencesDialog({ onClose }: Props) {
  const [prefs, setPrefs] = useState<Prefs>(loadPrefs);

  useEffect(() => { savePrefs(prefs); }, [prefs]);

  const update = (key: keyof Prefs, value: unknown) => setPrefs(p => ({ ...p, [key]: value }));

  return (
    <div data-testid="preferences-dialog" style={{
      position: 'fixed', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'rgba(0,0,0,0.4)', zIndex: 9999,
    }}>
      <div style={{ background: '#f0f0f0', border: '1px solid #888', borderRadius: 4, padding: 16, minWidth: 400, maxWidth: 500 }}>
        <h3 style={{ margin: '0 0 12px', fontSize: 14 }}>Preferences</h3>

        <fieldset style={{ border: '1px solid #ccc', borderRadius: 3, padding: 8, marginBottom: 8 }}>
          <legend style={{ fontSize: 12, fontWeight: 'bold' }}>General</legend>
          <label style={{ display: 'flex', alignItems: 'center', fontSize: 12, marginBottom: 4 }}>
            Background:
            <select value={prefs.defaultBgColor} onChange={e => update('defaultBgColor', e.target.value)} style={{ marginLeft: 8 }}>
              <option value="dark">Dark</option><option value="light">Light</option><option value="white">White</option>
            </select>
          </label>
          <label style={{ display: 'flex', alignItems: 'center', fontSize: 12, marginBottom: 4 }}>
            Mesh Color: <input type="color" value={prefs.defaultMeshColor} onChange={e => update('defaultMeshColor', e.target.value)} style={{ marginLeft: 8 }} />
          </label>
          <label style={{ display: 'flex', alignItems: 'center', fontSize: 12, marginBottom: 4 }}>
            Max Undo: <input type="number" value={prefs.maxUndoHistory} min={1} max={100} onChange={e => update('maxUndoHistory', +e.target.value)} style={{ marginLeft: 8, width: 60 }} />
          </label>
        </fieldset>

        <fieldset style={{ border: '1px solid #ccc', borderRadius: 3, padding: 8, marginBottom: 8 }}>
          <legend style={{ fontSize: 12, fontWeight: 'bold' }}>Rendering</legend>
          <label style={{ display: 'flex', alignItems: 'center', fontSize: 12, marginBottom: 4 }}>
            Default Mode:
            <select value={prefs.defaultRenderMode} onChange={e => update('defaultRenderMode', e.target.value)} style={{ marginLeft: 8 }}>
              <option value="solid">Smooth</option><option value="flat">Flat</option><option value="wireframe">Wire</option><option value="points">Points</option>
            </select>
          </label>
          <label style={{ display: 'flex', alignItems: 'center', fontSize: 12, marginBottom: 4 }}>
            <input type="checkbox" checked={prefs.defaultSSAO} onChange={e => update('defaultSSAO', e.target.checked)} /> SSAO by default
          </label>
          <label style={{ display: 'flex', alignItems: 'center', fontSize: 12, marginBottom: 4 }}>
            <input type="checkbox" checked={prefs.defaultShadows} onChange={e => update('defaultShadows', e.target.checked)} /> Shadows by default
          </label>
        </fieldset>

        <fieldset style={{ border: '1px solid #ccc', borderRadius: 3, padding: 8, marginBottom: 12 }}>
          <legend style={{ fontSize: 12, fontWeight: 'bold' }}>Tools</legend>
          <label style={{ display: 'flex', alignItems: 'center', fontSize: 12, marginBottom: 4 }}>
            Brush Size: <input type="number" value={prefs.defaultBrushSize} min={1} max={100} onChange={e => update('defaultBrushSize', +e.target.value)} style={{ marginLeft: 8, width: 60 }} />
          </label>
          <label style={{ display: 'flex', alignItems: 'center', fontSize: 12, marginBottom: 4 }}>
            Selection Color: <input type="color" value={prefs.selectionColor} onChange={e => update('selectionColor', e.target.value)} style={{ marginLeft: 8 }} />
          </label>
        </fieldset>

        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <button onClick={() => { setPrefs({ ...DEFAULT_PREFS }); }} style={{ padding: '4px 12px', fontSize: 12 }}>Reset Defaults</button>
          <button onClick={onClose} style={{ padding: '4px 16px', fontSize: 12, fontWeight: 'bold' }}>Close</button>
        </div>
      </div>
    </div>
  );
}
