import { Database, Globe2, Save, ShieldCheck } from "lucide-solid";
import { createEffect, createSignal } from "solid-js";
import { displayApiBase } from "../../lib/api";
import { PageHeading } from "../../components/ui/page-heading";
import type { PageProps } from "../types";

export default function SettingsPage(props: PageProps) {
  const [endpoint, setEndpoint] = createSignal("");
  let initialized = false;
  createEffect(() => {
    const state = props.state();
    if (state && !initialized) {
      setEndpoint(state.apiBase);
      initialized = true;
    }
  });

  return (
    <main class="page">
      <PageHeading
        eyebrow="CONFIGURATION"
        title="运行设置"
        description="配置管理 API 连接；运行边界由后端策略统一控制。"
      />
      <div class="grid gap-5 xl:grid-cols-[minmax(0,1.4fr)_minmax(280px,0.7fr)]">
        <section class="panel">
          <div class="panel-header">
            <div>
              <h2>管理 API</h2>
              <p>留空表示使用当前页面同源地址</p>
            </div>
            <Globe2 size={18} class="text-cyan-strong" />
          </div>
          <form
            class="p-5"
            onSubmit={(event) => {
              event.preventDefault();
              props.command({ type: "save-api-base", value: endpoint() });
            }}
          >
            <label class="field">
              <span>Endpoint</span>
              <input
                class="input"
                type="url"
                value={endpoint()}
                placeholder={window.location.origin}
                onInput={(event) => setEndpoint(event.currentTarget.value)}
              />
            </label>
            <p class="mt-2 text-xs text-muted">
              当前解析地址：{displayApiBase(props.state()?.apiBase ?? "")}
            </p>
            <div class="mt-5 flex justify-end">
              <button class="btn btn-primary" type="submit">
                <Save size={15} />
                保存连接
              </button>
            </div>
          </form>
        </section>
        <aside class="space-y-3">
          <Info
            icon={ShieldCheck}
            title="Sandbox"
            detail="网络与 Host 能力默认拒绝，按 WIT import 精确链接。"
          />
          <Info icon={Database} title="持久化" detail="控制状态和服务 KV 存储于本地 libSQL。" />
        </aside>
      </div>
    </main>
  );
}

function Info(props: { icon: typeof ShieldCheck; title: string; detail: string }) {
  const Icon = props.icon;
  return (
    <article class="panel flex gap-3 p-4">
      <span class="flex size-9 shrink-0 items-center justify-center rounded-md bg-brand-soft text-brand">
        <Icon size={16} />
      </span>
      <div>
        <strong class="text-sm">{props.title}</strong>
        <p class="mt-1 text-xs leading-5 text-muted">{props.detail}</p>
      </div>
    </article>
  );
}
