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

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

function qualityColor(q: string): string {
  switch (q) {
    case 'good': return '#4ade80';
    case 'uncertain': return '#fbbf24';
    case 'bad': return '#f87171';
    default: return '#6b7280';
  }
}

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

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

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

  const label = widget.options['label'] || sigRef?.name || '';
  const rawUnit = widget.options['unit'];
  const unit = rawUnit === 'none' ? '' : (rawUnit || meta?.unit || '');
  const quality = sv.quality;
  const fmt = widget.options['format'] ?? '';

  function displayValue(): string {
    if (!sv || sv.value === null || sv.value === undefined) return '---';
    const v = sv.value;
    if (typeof v === 'number') return formatValue(v, fmt);
    return String(v);
  }

  return (
    <div
      class="textview"
      style={`left:${widget.x}px;top:${widget.y}px;width:${widget.w}px;height:${widget.h}px;`}
      onContextMenu={onContextMenu}
    >
      <span class="quality-dot" style={`background:${qualityColor(quality)};`} title={`Quality: ${quality}`} />
      <span class="label">{label}:</span>
      <span class="value">{displayValue()}</span>
      {unit && <span class="unit">{unit}</span>}
    </div>
  );
}
