"use client";

import {
  ALERT_SOUND_CHANGED_EVENT,
  ALERT_SOUND_OPTIONS,
  loadAlertSoundSettings,
  notifyAlertSoundChanged,
  saveAlertSoundSettings,
  type AlertSoundId,
} from "@/lib/alerts/sound-settings";
import { previewAlertSound, unlockAlertAudio } from "@/lib/alerts/play-alert-sound";
import { useCallback, useEffect, useState } from "react";

export function AlertSoundSettings() {
  const [settings, setSettings] = useState(loadAlertSoundSettings);

  const persist = useCallback((next: typeof settings) => {
    setSettings(next);
    saveAlertSoundSettings(next);
    notifyAlertSoundChanged();
  }, []);

  useEffect(() => {
    const sync = () => setSettings(loadAlertSoundSettings());
    window.addEventListener(ALERT_SOUND_CHANGED_EVENT, sync);
    return () => window.removeEventListener(ALERT_SOUND_CHANGED_EVENT, sync);
  }, []);

  return (
    <div className="alert-sound-settings">
      <label className="toolbar-check-row">
        <input
          type="checkbox"
          checked={settings.enabled}
          onChange={(e) => persist({ ...settings, enabled: e.target.checked })}
        />
        <span>Alert sound</span>
      </label>
      <label className="toolbar-field">
        <span className="toolbar-label">Sound</span>
        <select
          value={settings.soundId}
          disabled={!settings.enabled}
          onChange={(e) => {
            const soundId = e.target.value as AlertSoundId;
            persist({ ...settings, soundId });
          }}
        >
          {ALERT_SOUND_OPTIONS.map((o) => (
            <option key={o.id} value={o.id}>
              {o.label}
            </option>
          ))}
        </select>
      </label>
      <label className="toolbar-field">
        <span className="toolbar-label">Volume</span>
        <input
          type="range"
          min={0.1}
          max={1}
          step={0.05}
          value={settings.volume}
          disabled={!settings.enabled}
          onChange={(e) =>
            persist({ ...settings, volume: Number.parseFloat(e.target.value) })
          }
        />
      </label>
      <button
        type="button"
        className="toolbar-btn toolbar-btn-sm"
        disabled={!settings.enabled}
        onClick={() => {
          unlockAlertAudio();
          previewAlertSound(settings.soundId, settings.volume);
        }}
      >
        Test sound
      </button>
    </div>
  );
}
