import app from 'flarum/forum/app';
import { extend } from 'flarum/common/extend';
import SettingsPage from 'flarum/forum/components/SettingsPage';
import Switch from 'flarum/common/components/Switch';
import Component from 'flarum/common/Component';

class TeamsSettingsBlock extends Component {
  oninit(vnode) {
    super.oninit(vnode);

    // Serielle Saves verhindern "Überholen" bei schnellen Klicks.
    this.saveChain = Promise.resolve();
  }

  queueSave(user, preferences) {
    this.saveChain = this.saveChain.then(() => user.savePreferences(preferences));
    return this.saveChain;
  }

  view() {
    const user = app.session.user;
    if (!user) return null;

    return (
      <div className="TeamsSettings Block">
        <h3>Microsoft Teams</h3>

        {this.prefSwitch(
          user,
          'sbp-jm-msteams.enabled',
          'Enable Microsoft Teams notifications'
        )}

        <div className="TeamsSettings-options">
          {this.prefSwitch(
            user,
            'sbp-jm-msteams.types.newPost',
            'Someone replies to a discussion I am following'
          )}

          {this.prefSwitch(
            user,
            'sbp-jm-msteams.types.postMentioned',
            'Someone mentions me in a post'
          )}

          {this.prefSwitch(
            user,
            'sbp-jm-msteams.types.userMentioned',
            'Someone mentions me'
          )}
        </div>
      </div>
    );
  }

  prefSwitch(user, key, label) {
    const prefs = user.preferences() || {};

    return (
      <Switch
        state={!!prefs[key]}
        onchange={(value) => {
          const before = user.preferences() || {};

          // ✅ KORREKT: Key dynamisch setzen
          const merged = {
            ...before,
            [key]: value,
          };

          // Debug-Ausgaben (hilft beim Verifizieren)
          console.log('[msteams prefs] key', key, 'value', value);
          console.log('[msteams prefs] before', before);
          console.log('[msteams prefs] merged', merged);

          return this.queueSave(user, merged).then(() => {
            console.log('[msteams prefs] after', user.preferences() || {});
          });
        }}
      >
        {label}
      </Switch>
    );
  }
}

export default function addTeamsSettings() {
  extend(SettingsPage.prototype, 'content', function (vnode) {
    vnode.children.push(<TeamsSettingsBlock />);
  });
}