import type { Node } from "@xyflow/react";
import { NODE_KINDS, type Specialist } from "./nodeCatalog";

const inputCls =
  "mt-1 w-full rounded-md border border-line bg-ink-800 px-2 py-1 text-sm text-slate-200 focus:border-violet-500/60 focus:outline-none";
const cardCls =
  "w-full rounded border border-line bg-ink-800 px-2 py-1 text-[12px] text-slate-200 placeholder:text-slate-600 focus:border-indigo-500/60 focus:outline-none";

// AgentListField：多智能体协调节点的「子智能体(专家)」配置 —— 可增删的专家卡片。
// 每张卡片对齐后端 parseSpecialists 的 {name, use, system, tools}。
function AgentListField({ value, onChange }: { value: Specialist[]; onChange: (next: Specialist[]) => void }) {
  const list = Array.isArray(value) ? value : [];
  const update = (i: number, patch: Partial<Specialist>) => onChange(list.map((s, idx) => (idx === i ? { ...s, ...patch } : s)));
  const add = () => onChange([...list, { name: "", use: "", system: "", tools: [] }]);
  const remove = (i: number) => onChange(list.filter((_, idx) => idx !== i));
  return (
    <div className="mt-1 space-y-2">
      {list.map((s, i) => (
        <div key={i} className="space-y-1.5 rounded-md border border-indigo-500/20 bg-ink-950/40 p-2">
          <div className="flex items-center gap-2">
            <input className={cardCls} placeholder="专家名（如 legal）" value={s.name} onChange={(e) => update(i, { name: e.target.value })} />
            <button onClick={() => remove(i)} className="shrink-0 text-[11px] text-rose-400 hover:underline">
              删除
            </button>
          </div>
          <input className={cardCls} placeholder="用途/擅长（lead 据此判断何时派给它）" value={s.use} onChange={(e) => update(i, { use: e.target.value })} />
          <textarea
            className={`${cardCls} h-12 resize-none`}
            placeholder="系统提示词（专家人设）"
            value={s.system}
            onChange={(e) => update(i, { system: e.target.value })}
          />
          <input
            className={cardCls}
            placeholder="工具（逗号分隔，可空；如 wiki_search, kb_search）"
            value={(s.tools ?? []).join(", ")}
            onChange={(e) => update(i, { tools: e.target.value.split(",").map((t) => t.trim()).filter(Boolean) })}
          />
        </div>
      ))}
      <button
        onClick={add}
        className="w-full rounded border border-dashed border-line py-1 text-[11px] text-slate-400 hover:border-indigo-500/50 hover:text-indigo-300"
      >
        + 添加专家
      </button>
    </div>
  );
}

// 右检查器：按选中节点的类型渲染配置表单；空选时显示图级提示（深色）。
export function Inspector({
  node,
  onChange,
  onDelete,
  dynamicOptions,
}: {
  node: Node | null;
  onChange: (id: string, patch: Record<string, unknown>) => void;
  onDelete: (id: string) => void;
  dynamicOptions?: Record<string, string[]>; // 运行时选项（如 kb=真实知识库、model=已登记模型）
}) {
  if (!node) {
    return (
      <div className="p-4 text-xs leading-relaxed text-slate-500">
        选中一个节点查看/编辑配置。
        <br />
        从左侧面板添加节点，拖动连线编排。
      </div>
    );
  }
  const data = node.data as { kind: string; label?: string; config?: Record<string, unknown> };
  const k = NODE_KINDS[data.kind] ?? NODE_KINDS.output;
  const config = data.config ?? {};
  const setConfig = (key: string, value: unknown) => onChange(node.id, { config: { ...config, [key]: value } });

  return (
    <div className="flex h-full flex-col">
      <div className="flex items-center justify-between border-b border-line p-3">
        <span className={`rounded px-1.5 py-0.5 text-[11px] font-medium ${k.badge}`}>{k.label}</span>
        <button onClick={() => onDelete(node.id)} className="text-xs text-rose-400 hover:underline">
          删除
        </button>
      </div>
      <div className="flex flex-col gap-3 overflow-auto p-3">
        <label className="text-xs text-slate-500">
          标签
          <input className={inputCls} value={data.label ?? ""} onChange={(e) => onChange(node.id, { label: e.target.value })} />
        </label>
        {k.fields.map((f) => {
          const v = config[f.key];
          return (
            <label key={f.key} className="text-xs text-slate-500">
              {f.label}
              {f.required && <span className="text-rose-400"> *</span>}
              {f.type === "agentList" ? (
                <AgentListField value={(v as Specialist[]) ?? []} onChange={(next) => setConfig(f.key, next)} />
              ) : f.type === "select" ? (
                (() => {
                  const dyn = dynamicOptions?.[f.key];
                  const opts = dyn && dyn.length ? dyn : f.options ?? [];
                  return (
                    <select className={inputCls} value={String(v ?? "")} onChange={(e) => setConfig(f.key, e.target.value)}>
                      {dyn && dyn.length === 0 && <option value="">（无，先到知识库/控制台创建）</option>}
                      {opts.map((o) => (
                        <option key={o}>{o}</option>
                      ))}
                    </select>
                  );
                })()
              ) : f.type === "textarea" ? (
                <textarea
                  className={`${inputCls} h-16 resize-none`}
                  value={String(v ?? "")}
                  placeholder={f.placeholder}
                  onChange={(e) => setConfig(f.key, e.target.value)}
                />
              ) : f.type === "checkbox" ? (
                <input type="checkbox" className="ml-2 align-middle accent-violet-500" checked={Boolean(v)} onChange={(e) => setConfig(f.key, e.target.checked)} />
              ) : (
                <input
                  type={f.type === "number" ? "number" : "text"}
                  className={inputCls}
                  value={String(v ?? "")}
                  placeholder={f.placeholder}
                  onChange={(e) => setConfig(f.key, f.type === "number" ? Number(e.target.value) : e.target.value)}
                />
              )}
            </label>
          );
        })}
      </div>
    </div>
  );
}
