import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { createSignal, onMount, onCleanup } from 'solid-js';

interface PingResponse {
  message: string;
  counter: number;
}

export function IpcDemo() {
  const [pingCount, setPingCount] = createSignal(0);
  const [pingResult, setPingResult] = createSignal<PingResponse | null>(null);
  const [greetResult, setGreetResult] = createSignal('');
  const [backendEvent, setBackendEvent] = createSignal('Waiting for backend...');

  // Frontend -> Rust: invoke ping command
  const handlePing = async () => {
    const result = await invoke<PingResponse>('ping', { count: pingCount() });
    setPingResult(result);
    setPingCount(result.counter);
  };

  // Frontend -> Rust: invoke greet command
  const handleGreet = async () => {
    const result = await invoke<string>('greet', { name: 'HoloHue' });
    setGreetResult(result);
  };

  // Rust -> Frontend: listen for backend-ready event
  onMount(async () => {
    const unlisten = await listen<PingResponse>('backend-ready', (event) => {
      setBackendEvent(event.payload.message);
    });
    onCleanup(() => unlisten());
  });

  return (
    <div class="space-y-4">
      <h2 class="text-lg font-bold text-secondary font-display hh-divider-glow">IPC Bridge Demo</h2>

      {/* Backend event status */}
      <div class="hh-panel">
        <h3 class="mb-2 text-sm font-semibold text-text-muted font-display">
          Rust -&gt; Frontend (Event)
        </h3>
        <p class="text-sm text-text-muted font-mono">{backendEvent()}</p>
      </div>

      {/* Ping/Pong demo */}
      <div class="hh-panel">
        <h3 class="mb-2 text-sm font-semibold text-text-muted font-display">
          Frontend -&gt; Rust (Invoke: ping)
        </h3>
        <button onClick={handlePing} class="hh-btn">
          Ping Rust
        </button>
        {pingResult() && (
          <p class="mt-2 text-sm text-text-muted font-mono">
            Response: {pingResult()!.message} (counter: {pingResult()!.counter})
          </p>
        )}
      </div>

      {/* Greet demo */}
      <div class="hh-panel">
        <h3 class="mb-2 text-sm font-semibold text-text-muted font-display">
          Frontend -&gt; Rust (Invoke: greet)
        </h3>
        <button onClick={handleGreet} class="hh-btn">
          Greet from Rust
        </button>
        {greetResult() && (
          <p class="mt-2 text-sm text-text-muted font-mono">{greetResult()}</p>
        )}
      </div>
    </div>
  );
}
