import {
  Activity,
  AlertTriangle,
  CircleStop,
  CloudUpload,
  Cpu,
  Package,
  Play,
  RefreshCw,
  RotateCcw,
  Zap,
} from "lucide-solid";
import { createMemo, For, Show, type JSXElement } from "solid-js";
import { Page } from "../../components/layout/page";
import { PageHeading } from "../../components/layout/page-heading";
import { ServiceTable } from "../../components/services/service-table";
import { Button, IconButton } from "../../components/ui/button";
import { Card, CardHeader } from "../../components/ui/card";
import { eventsFrom, servicesFrom } from "../../lib/view-state";
import { formatDuration } from "../../lib/model";
import type { PageProps } from "../types";

export default function OverviewPage(props: PageProps) {
  const services = createMemo(() => servicesFrom(props.state()));
  const events = createMemo(() => eventsFrom(props.state()));
  const running = createMemo(
    () => services().filter((service) => service.status === "running").length,
  );
  const totalCalls = createMemo(() =>
    services().reduce((total, service) => total + service.calls, 0),
  );
  const errors = createMemo(() => services().reduce((total, service) => total + service.errors, 0));

  return (
    <Page>
      <Show when={props.state()} fallback={<OverviewSkeleton />}>
        {(state) => (
          <>
            <PageHeading
              eyebrow="LOCAL RUNTIME"
              title="运行概览"
              description={`${services().length} 个已注册版本，${running()} 个 Actor 正在运行。`}
              actions={
                <>
                  <IconButton
                    aria-label="刷新"
                    title="刷新"
                    onClick={() => props.command({ type: "refresh" })}
                  >
                    <RefreshCw size={16} />
                  </IconButton>
                  <Button
                    variant="primary"
                    onClick={() => props.command({ type: "open-register" })}
                  >
                    <CloudUpload size={16} />
                    注册组件
                  </Button>
                </>
              }
            />

            <section
              class="mb-5 grid grid-cols-1 border-l border-t border-line sm:grid-cols-2 xl:grid-cols-4"
              aria-label="关键指标"
            >
              <Metric
                icon={<Package size={18} />}
                tone="bg-cyan-soft text-cyan-strong"
                label="服务版本"
                value={services().length.toString()}
                note={`${state().snapshot?.deployments.length ?? 0} 个对外服务`}
              />
              <Metric
                icon={<Activity size={18} />}
                tone="bg-brand-soft text-brand"
                label="运行实例"
                value={running().toString()}
                note={`${services().length - running()} 个未运行`}
              />
              <Metric
                icon={<Zap size={18} />}
                tone="bg-amber-soft text-amber-strong"
                label="累计调用"
                value={totalCalls().toLocaleString("zh-CN")}
                note="持久化统计"
              />
              <Metric
                icon={<AlertTriangle size={18} />}
                tone="bg-coral-soft text-coral-strong"
                label="调用异常"
                value={errors().toString()}
                note={errors() > 0 ? "需要检查" : "无异常"}
              />
            </section>

            <Card
              as="section"
              class="mb-5 grid lg:grid-cols-[minmax(280px,1.4fr)_repeat(3,minmax(130px,1fr))]"
            >
              <div class="flex items-center gap-3 border-b border-line px-5 py-4 lg:border-b-0 lg:border-r">
                <span class="flex size-10 items-center justify-center rounded-md bg-brand-soft text-brand">
                  <Cpu size={18} />
                </span>
                <div class="min-w-0 flex-1">
                  <strong class="block">Wasmeld Runtime</strong>
                  <span class="mt-0.5 block truncate text-xs text-muted">
                    {state().snapshot?.runtime.status === "running"
                      ? "Wasmtime sandbox 正常"
                      : "Engine 与 Actor 已释放"}
                  </span>
                </div>
                <div class="flex gap-1">
                  <Show
                    when={state().snapshot?.runtime.status === "running"}
                    fallback={
                      <IconButton
                        aria-label="启动 Runtime"
                        title="启动 Runtime"
                        disabled={state().runtimeAction !== null}
                        onClick={() => props.command({ type: "runtime-action", action: "start" })}
                      >
                        <Play size={15} />
                      </IconButton>
                    }
                  >
                    <IconButton
                      aria-label="重启 Runtime"
                      title="重启 Runtime"
                      disabled={state().runtimeAction !== null}
                      onClick={() => props.command({ type: "runtime-action", action: "restart" })}
                    >
                      <RotateCcw size={15} />
                    </IconButton>
                    <IconButton
                      tone="danger"
                      aria-label="停止 Runtime"
                      title="停止 Runtime"
                      disabled={state().runtimeAction !== null}
                      onClick={() => props.command({ type: "runtime-action", action: "stop" })}
                    >
                      <CircleStop size={15} />
                    </IconButton>
                  </Show>
                </div>
              </div>
              <RuntimeStat
                label="已加载版本"
                value={(state().snapshot?.runtime.registered_services ?? 0).toString()}
                detail="已编译 Component"
              />
              <RuntimeStat
                label="活跃 Store"
                value={(state().snapshot?.runtime.running_services ?? 0).toString()}
                detail="串行 Actor"
              />
              <RuntimeStat
                label="运行时间"
                value={
                  state().snapshot?.runtime.status === "running"
                    ? formatDuration(state().snapshot?.runtime.uptime_ms ?? 0)
                    : "—"
                }
                detail="当前 Runtime"
              />
            </Card>

            <div class="grid gap-5 xl:grid-cols-[minmax(0,1.7fr)_minmax(300px,0.8fr)]">
              <Card as="section" class="min-w-0">
                <CardHeader>
                  <div>
                    <h2>服务状态</h2>
                    <p>已注册版本及当前 Actor 状态</p>
                  </div>
                  <Button
                    size="small"
                    onClick={() => props.command({ type: "navigate", view: "services" })}
                  >
                    查看全部
                  </Button>
                </CardHeader>
                <ServiceTable
                  services={services().slice(0, 5)}
                  state={state()}
                  command={props.command}
                  compact
                />
              </Card>

              <Card as="aside">
                <CardHeader>
                  <div>
                    <h2>最近事件</h2>
                    <p>生命周期与调用结果</p>
                  </div>
                  <span class="inline-flex items-center gap-1.5 text-[11px] font-bold text-brand">
                    <span class="size-1.5 rounded-full bg-brand" />
                    LIVE
                  </span>
                </CardHeader>
                <div class="divide-y divide-line">
                  <For
                    each={events().slice(0, 6)}
                    fallback={<p class="px-5 py-12 text-center text-sm text-muted">暂无事件</p>}
                  >
                    {(event) => (
                      <div class="px-5 py-3">
                        <div class="flex items-center justify-between gap-3">
                          <strong class="truncate text-xs">{event.title}</strong>
                          <span class="font-mono text-[10px] text-muted">{event.time}</span>
                        </div>
                        <p class="mt-1 line-clamp-2 text-xs leading-5 text-muted">{event.detail}</p>
                      </div>
                    )}
                  </For>
                </div>
              </Card>
            </div>
          </>
        )}
      </Show>
    </Page>
  );
}

function Metric(props: {
  icon: JSXElement;
  tone: string;
  label: string;
  value: string;
  note: string;
}) {
  return (
    <article class="flex min-h-24 items-center gap-3 border-b border-r border-line bg-white px-4 py-3">
      <div class={`flex size-10 shrink-0 items-center justify-center rounded-md ${props.tone}`}>
        {props.icon}
      </div>
      <div class="min-w-0 flex-1">
        <span class="block text-xs text-muted">{props.label}</span>
        <strong class="mt-1 block text-2xl font-bold">{props.value}</strong>
      </div>
      <small class="self-end whitespace-nowrap pb-1 text-[11px] text-muted">{props.note}</small>
    </article>
  );
}

function RuntimeStat(props: { label: string; value: string; detail: string }) {
  return (
    <div class="border-b border-line px-5 py-4 last:border-b-0 lg:border-b-0 lg:border-r lg:last:border-r-0">
      <span class="block text-xs text-muted">{props.label}</span>
      <strong class="mt-1 block text-lg">{props.value}</strong>
      <small class="mt-0.5 block text-[11px] text-muted">{props.detail}</small>
    </div>
  );
}

function OverviewSkeleton() {
  return (
    <div class="space-y-5 py-5">
      <div class="h-3 w-36 animate-pulse rounded-sm bg-[#dfe6e4]" />
      <div class="h-8 w-64 animate-pulse rounded-sm bg-[#dfe6e4]" />
      <div class="grid grid-cols-2 gap-3 lg:grid-cols-4">
        <For each={[1, 2, 3, 4]}>{() => <div class="h-24 animate-pulse bg-white" />}</For>
      </div>
    </div>
  );
}
