import { History, RefreshCw } from "lucide-solid";
import { createMemo, For, onCleanup, Show } from "solid-js";
import { EmptyState } from "../../components/feedback/empty-state";
import { Page } from "../../components/layout/page";
import { PageHeading } from "../../components/layout/page-heading";
import { IconButton } from "../../components/ui/button";
import { Card } from "../../components/ui/card";
import { eventsFrom } from "../../lib/view-state";
import type { PageProps } from "../types";

const toneClass = {
  success: "bg-brand",
  warning: "bg-amber-strong",
  danger: "bg-coral-strong",
  neutral: "bg-muted",
};

export default function ActivityPage(props: PageProps) {
  // A retained Activity iframe may have been hidden for a while. Request a
  // fresh snapshot whenever it becomes visible instead of waiting for the
  // Host's next background poll.
  onCleanup(props.lifecycle.onShow(() => props.command({ type: "refresh" })));

  const events = createMemo(() => {
    const query = props.state()?.query.trim().toLowerCase() ?? "";
    return eventsFrom(props.state()).filter(
      (event) =>
        !query ||
        event.title.toLowerCase().includes(query) ||
        event.detail.toLowerCase().includes(query),
    );
  });

  return (
    <Page>
      <PageHeading
        eyebrow="EVENTS"
        title="调用记录"
        description="最近 256 条持久化生命周期与调用事件。"
        actions={
          <IconButton
            aria-label="刷新"
            title="刷新"
            onClick={() => props.command({ type: "refresh" })}
          >
            <RefreshCw size={16} />
          </IconButton>
        }
      />
      <Card as="section">
        <Show
          when={events().length > 0}
          fallback={
            <EmptyState icon={History} title="暂无事件" detail="Runtime 操作和调用会显示在这里。" />
          }
        >
          <div class="divide-y divide-line">
            <For each={events()}>
              {(event) => (
                <article class="grid gap-2 px-5 py-4 sm:grid-cols-[10px_minmax(180px,0.8fr)_2fr_84px] sm:items-center">
                  <span class={`size-2 rounded-full ${toneClass[event.tone]}`} />
                  <strong class="text-sm">{event.title}</strong>
                  <p class="text-xs leading-5 text-muted">{event.detail}</p>
                  <time class="font-mono text-xs text-muted sm:text-right">{event.time}</time>
                </article>
              )}
            </For>
          </div>
        </Show>
      </Card>
    </Page>
  );
}
