import { h } from 'preact';
import { useState, useMemo, useEffect } from 'preact/hooks';
import InterfaceList from './InterfaceList';
import Canvas from './Canvas';
import { wsClient } from './lib/ws';
import { parseInterface } from './lib/xml';
import type { Interface } from './lib/types';
import ContextualHelp from './ContextualHelp';
import HelpModal from './HelpModal';

interface Props {
  onEdit?: (iface?: Interface) => void;
}

/** Format a Date as a datetime-local input value (YYYY-MM-DDTHH:MM) */
function toLocalInput(d: Date): string {
  const pad = (n: number) => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

export default function ViewMode({ onEdit }: Props) {
  const [currentInterface, setCurrentInterface] = useState<Interface | null>(null);
  const [parseError, setParseError] = useState<string | null>(null);
  const [wsStatus, setWsStatus] = useState('connecting');
  const [showHelp, setShowHelp] = useState(false);
  const [helpSection, setHelpSection] = useState('start');
  const [showTimeNav, setShowTimeNav] = useState(false);

  function openHelp(section = 'start') { setHelpSection(section); setShowHelp(true); }

  // Historical time range — null means live
  const now = useMemo(() => new Date(), []);
  const [startInput, setStartInput] = useState(() => toLocalInput(new Date(now.getTime() - 3600_000)));
  const [endInput, setEndInput]     = useState(() => toLocalInput(now));
  const [timeRange, setTimeRange]   = useState<{ start: string; end: string } | null>(null);

  useEffect(() => {
    const unsub = wsClient.status.subscribe(setWsStatus);
    return unsub;
  }, []);

  function handleLoad(xml: string) {
    try {
      setParseError(null);
      setCurrentInterface(parseInterface(xml));
    } catch (err) {
      setParseError(err instanceof Error ? err.message : 'Failed to parse interface file.');
    }
  }

  async function handleNavigate(interfaceId: string) {
    try {
      const res = await fetch(`/api/v1/interfaces/${encodeURIComponent(interfaceId)}`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      handleLoad(await res.text());
    } catch (err) {
      setParseError(`Failed to load interface "${interfaceId}": ${err instanceof Error ? err.message : err}`);
    }
  }

  /** Load interface by ID and pass parsed object to onEdit */
  async function handleEditById(id: string) {
    try {
      const res = await fetch(`/api/v1/interfaces/${encodeURIComponent(id)}`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const iface = parseInterface(await res.text());
      onEdit?.(iface);
    } catch (err) {
      setParseError(`Failed to load interface for editing: ${err instanceof Error ? err.message : err}`);
    }
  }

  function handleLoadHistory() {
    if (!startInput || !endInput) return;
    const start = new Date(startInput).toISOString();
    const end   = new Date(endInput).toISOString();
    setTimeRange({ start, end });
  }

  function handleGoLive() {
    setTimeRange(null);
  }

  const isLive = timeRange === null;

  return (
    <div class="view-mode">
      <header class="toolbar">
        <div class="toolbar-left">
          <span class="app-name">uopi</span>
          {currentInterface && (
            <span class="iface-name">{currentInterface.name}</span>
          )}
        </div>
        <div class="toolbar-center">
          {parseError && (
            <span class="parse-error" title={parseError}>Parse error — check console</span>
          )}
        </div>
        <div class="toolbar-right">
          <div class={`status-chip ${wsStatus}`}>
            <span class="status-dot"></span>
            {wsStatus}
          </div>
          <button
            class={`toolbar-btn${showTimeNav ? ' toolbar-btn-active' : ''}`}
            title="Toggle historical time navigation"
            onClick={() => setShowTimeNav(v => !v)}
          >
            ⏱ History
          </button>
          <ContextualHelp mode="view" onOpenManual={openHelp} />
          <button
            class="icon-btn help-manual-btn"
            onClick={() => openHelp('start')}
            title="Open user manual"
          >
            📖
          </button>
          <button
            class="btn-edit"
            onClick={() => onEdit?.(currentInterface ?? undefined)}
            title="Switch to Edit mode"
          >
            Edit
          </button>
        </div>
      </header>

      {/* Historical time range bar — hidden by default */}
      {showTimeNav && (
        <div class="time-nav-bar">
          <button
            class={`toolbar-btn${isLive ? ' toolbar-btn-active' : ''}`}
            title="Switch to live data"
            onClick={handleGoLive}
          >
            ● Live
          </button>
          <input
            class="time-input"
            type="datetime-local"
            value={startInput}
            onInput={(e) => setStartInput((e.target as HTMLInputElement).value)}
            title="History start"
          />
          <span class="time-sep">→</span>
          <input
            class="time-input"
            type="datetime-local"
            value={endInput}
            onInput={(e) => setEndInput((e.target as HTMLInputElement).value)}
            title="History end"
          />
          <button
            class="toolbar-btn"
            title="Load historical data for this time range"
            onClick={handleLoadHistory}
          >
            Load
          </button>
        </div>
      )}

      <div class="content">
        <InterfaceList
          onLoad={handleLoad}
          onEdit={onEdit}
          onEditId={handleEditById}
          onSelect={async (id) => {
            try {
              const res = await fetch(`/api/v1/interfaces/${encodeURIComponent(id)}`);
              if (!res.ok) throw new Error(`HTTP ${res.status}`);
              handleLoad(await res.text());
            } catch (err) {
              setParseError(`Failed to load interface "${id}": ${err instanceof Error ? err.message : err}`);
            }
          }}
        />
        <Canvas iface={currentInterface} onNavigate={handleNavigate} timeRange={timeRange} />
      </div>

      {showHelp && (
        <HelpModal initialSection={helpSection} onClose={() => setShowHelp(false)} />
      )}
    </div>
  );
}
