import { useEffect, useState } from 'react';
import { applyFontSize, applyTheme, loadAppearance, saveAppearance, type FontSize, type Theme } from '../appearance';

export default function AppearancePage() {
  const [theme, setTheme] = useState<Theme>('light');
  const [size, setSize] = useState<FontSize>('medium');

  useEffect(() => {
    const { theme, size } = loadAppearance();
    setTheme(theme);
    setSize(size);
  }, []);

  function onThemeChange(next: Theme) {
    setTheme(next);
    applyTheme(next);
    saveAppearance(next, size);
  }

  function onSizeChange(next: FontSize) {
    setSize(next);
    applyFontSize(next);
    saveAppearance(theme, next);
  }

  return (
    <section className="card">
      <h3>Appearance</h3>
      <div className="space-y">
        <div>
          <div className="muted" style={{ marginBottom: 6 }}>Theme</div>
          <div className="segmented">
            <button className={theme === 'light' ? 'active' : ''} onClick={() => onThemeChange('light')}>Light</button>
            <button className={theme === 'dark' ? 'active' : ''} onClick={() => onThemeChange('dark')}>Dark</button>
            <button className={theme === 'system' ? 'active' : ''} onClick={() => onThemeChange('system')}>System</button>
          </div>
        </div>
        <div>
          <div className="muted" style={{ marginBottom: 6 }}>Font size</div>
          <div className="segmented">
            <button className={size === 'small' ? 'active' : ''} onClick={() => onSizeChange('small')}>Small</button>
            <button className={size === 'medium' ? 'active' : ''} onClick={() => onSizeChange('medium')}>Medium</button>
            <button className={size === 'large' ? 'active' : ''} onClick={() => onSizeChange('large')}>Large</button>
          </div>
        </div>
      </div>
    </section>
  );
}
