import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { api } from "../../lib/api";

function principleLabel(raw: string) {
  if (!raw) return "";
  const parts = raw.split("#");
  return parts.length > 1 ? parts.slice(1).join("#") : raw;
}

function principleValue(id: string, title: string) {
  return `${id}#${title}`;
}

export function PrinciplePicker({
  value,
  onChange,
}: {
  value: string;
  onChange: (v: string) => void;
}) {
  const knowledgeQ = useQuery({ queryKey: ["knowledge"], queryFn: api.knowledge });
  const principles = knowledgeQ.data?.principles || [];

  const options = useMemo(
    () =>
      principles.map((p) => ({
        value: principleValue(p.id, p.title),
        label: p.title,
        summary: p.summary || p.body?.slice(0, 80),
      })),
    [principles],
  );

  const selected = options.find((o) => o.value === value || principleLabel(value) === o.label);

  return (
    <div className="settings-field">
      <label>依據心法</label>
      <select
        value={selected?.value || ""}
        onChange={(e) => onChange(e.target.value)}
        disabled={knowledgeQ.isLoading}
      >
        <option value="">— 選擇心法（可留空）—</option>
        {options.map((o) => (
          <option key={o.value} value={o.value}>
            {o.label}
          </option>
        ))}
      </select>
      {value && !selected ? (
        <input
          className="mt-s"
          value={principleLabel(value)}
          onChange={(e) => onChange(e.target.value)}
          placeholder="自訂心法"
        />
      ) : null}
      {selected?.summary ? <p className="small muted mt-s">{selected.summary}</p> : null}
    </div>
  );
}

export { principleLabel };