import { CloudUpload, Filter, RefreshCw } from "lucide-solid";
import { createMemo, createSignal, Show } 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 { Select } from "../../components/ui/select";
import { servicesFrom } from "../../lib/view-state";
import type { ServiceStatus } from "../../lib/model";
import type { PageProps } from "../types";

export default function ServicesPage(props: PageProps) {
  const [status, setStatus] = createSignal<"all" | ServiceStatus>("all");
  const services = createMemo(() => servicesFrom(props.state()));
  const filtered = createMemo(() => {
    const query = props.state()?.query.trim().toLowerCase() ?? "";
    return services().filter(
      (service) =>
        (status() === "all" || service.status === status()) &&
        (!query ||
          service.id.toLowerCase().includes(query) ||
          service.revision.toLowerCase().includes(query) ||
          service.artifact.toLowerCase().includes(query)),
    );
  });

  return (
    <Page>
      <PageHeading
        eyebrow="COMPONENTS"
        title="服务版本"
        description="管理不可变 Component Revision、Actor 状态和对外 Deployment。"
        actions={
          <>
            <label class="relative">
              <Filter
                class="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted"
                size={14}
              />
              <Select
                class="w-36 pl-9"
                value={status()}
                onChange={(event) => setStatus(event.currentTarget.value as "all" | ServiceStatus)}
              >
                <option value="all">全部状态</option>
                <option value="running">运行中</option>
                <option value="stopped">已停止</option>
                <option value="faulted">故障</option>
              </Select>
            </label>
            <Button variant="primary" onClick={() => props.command({ type: "open-register" })}>
              <CloudUpload size={16} />
              注册组件
            </Button>
          </>
        }
      />
      <Card as="section">
        <CardHeader>
          <div>
            <h2>已注册版本</h2>
            <p>{filtered().length} 个匹配项</p>
          </div>
          <IconButton
            aria-label="刷新"
            title="刷新"
            onClick={() => props.command({ type: "refresh" })}
          >
            <RefreshCw size={16} />
          </IconButton>
        </CardHeader>
        <Show when={props.state()}>
          {(state) => (
            <ServiceTable services={filtered()} state={state()} command={props.command} />
          )}
        </Show>
      </Card>
    </Page>
  );
}
