import { h } from 'preact';
import { useState, useEffect } from 'preact/hooks';
import { wsClient } from '../lib/ws';
import { getSignalStore } from '../lib/stores';
import type { Widget } from '../lib/types';

interface Props { widget: Widget; onContextMenu?: (e: MouseEvent) => void; }

export default function Button({ widget, onContextMenu }: Props) {
  const sigRef = widget.signals[0];
  const label      = widget.options['label']      ?? 'Button';
  const sendValue  = widget.options['value']      ?? '1';
  const resetValue = widget.options['resetValue'] ?? '0';
  // mode: oneshot | setReset | persistent
  const mode       = widget.options['mode']       ?? 'oneshot';
  const resetTimeSec = parseFloat(widget.options['resetTime'] ?? '1');
  const confirmOpt = widget.options['confirm'] === 'true';

  const [signalVal, setSignalVal] = useState<any>(null);

  // Subscribe to signal only for persistent mode (to track whether it is active)
  useEffect(() => {
    if (!sigRef || mode !== 'persistent') return;
    return getSignalStore(sigRef).subscribe(sv => setSignalVal(sv.value));
  }, [sigRef?.ds, sigRef?.name, mode]);

  const parsedSend  = isNaN(parseFloat(sendValue))  ? sendValue  : parseFloat(sendValue);
  const parsedReset = isNaN(parseFloat(resetValue)) ? resetValue : parseFloat(resetValue);

  // Persistent mode: button appears pressed while signal value matches sendValue
  const isPressed = mode === 'persistent'
    && signalVal !== null
    && String(signalVal) === String(parsedSend);

  function doWrite(val: any) {
    if (!sigRef) return;
    wsClient.write(sigRef, val);
  }

  function execute() {
    if (mode === 'setReset') {
      doWrite(parsedSend);
      setTimeout(() => doWrite(parsedReset), Math.max(0, resetTimeSec) * 1000);
    } else if (mode === 'persistent') {
      doWrite(isPressed ? parsedReset : parsedSend);
    } else {
      doWrite(parsedSend);
    }
  }

  function handleClick() {
    if (!sigRef) return;
    if (confirmOpt) {
      if (window.confirm(`Send ${label}?`)) execute();
    } else {
      execute();
    }
  }

  return (
    <div
      class="button-widget"
      style={`left:${widget.x}px;top:${widget.y}px;width:${widget.w}px;height:${widget.h}px;`}
      onContextMenu={onContextMenu}
    >
      <button class={`btn${isPressed ? ' btn-pressed' : ''}`} onClick={handleClick}>
        {label}
        {mode === 'setReset' && (
          <span class="btn-mode-hint">{resetTimeSec}s</span>
        )}
      </button>
    </div>
  );
}
