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

const DEFAULT_VALUE: SignalValue = { value: null, quality: 'unknown', ts: null };

function evaluateCondition(expr: string, v: any): boolean {
  if (/backtick|`|import|fetch|eval|Function|window|document/.test(expr)) return false;
  try {
    // eslint-disable-next-line no-new-func
    return new Function('value', 'return ' + expr)(v);
  } catch {
    return false;
  }
}

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

export default function Led({ widget, onContextMenu }: Props) {
  const sigRef = widget.signals[0];
  const [sv, setSv] = useState<SignalValue>(DEFAULT_VALUE);

  useEffect(() => {
    if (!sigRef) return;
    const unsub = getSignalStore(sigRef).subscribe(setSv);
    return unsub;
  }, [sigRef?.ds, sigRef?.name]);

  const label = widget.options['label'] ?? sigRef?.name ?? '';
  const condition = widget.options['condition'] ?? 'value > 0';
  const colorTrue = widget.options['colorTrue'] ?? '#22c55e';
  const colorFalse = widget.options['colorFalse'] ?? '#ef4444';

  const quality = sv.quality;
  const isUncertain = quality === 'uncertain' || quality === 'unknown';
  const ledOn = sv.value !== null && sv.value !== undefined ? evaluateCondition(condition, sv.value) : false;
  const ledColor = ledOn ? colorTrue : colorFalse;

  return (
    <div
      class="led-widget"
      style={`left:${widget.x}px;top:${widget.y}px;width:${widget.w}px;height:${widget.h}px;`}
      onContextMenu={onContextMenu}
    >
      <div
        class={`led-circle${isUncertain ? ' blink' : ''}`}
        style={`background:${ledColor};box-shadow:0 0 8px ${ledColor}88;`}
      />
      {label && <div class="led-label">{label}</div>}
    </div>
  );
}
