import { useState } from "react";
import { Check } from "lucide-react";
import { setMemory, type Identity } from "../lib/api";
import { Button, Input, Textarea, Field, useToast } from "../ui";

// 偏好记忆面板 —— 让用户显式登记/纠正模型对自己的记忆（→ PUT /api/v1/memory）。
export function MemoryPanel({ identity, onSaved }: { identity: Identity; onSaved?: () => void }) {
  const toast = useToast();
  const [key, setKey] = useState("回答偏好");
  const [value, setValue] = useState("简洁、中文、多给要点");
  const [saved, setSaved] = useState<Array<{ key: string; value: string }>>([]);

  const save = async () => {
    if (!key.trim()) return;
    try {
      const m = await setMemory(identity, key.trim(), value.trim());
      setSaved((s) => [{ key: key.trim(), value: value.trim() }, ...s.filter((x) => x.key !== key.trim())]);
      toast.push("success", m);
      onSaved?.();
    } catch (e) {
      toast.push("error", (e as Error).message);
    }
  };

  return (
    <section className="border-b border-line p-4">
      <h2 className="mb-3 text-sm font-semibold text-slate-300">偏好记忆（让模型知道是我）</h2>
      <div className="flex flex-col gap-3">
        <Field label="键">
          <Input value={key} onChange={(e) => setKey(e.target.value)} placeholder="如 称呼 / 回答偏好" />
        </Field>
        <Field label="值">
          <Textarea className="h-16 resize-none" value={value} onChange={(e) => setValue(e.target.value)} placeholder="值" />
        </Field>
        <Button variant="primary" size="sm" icon={Check} className="self-end" onClick={save}>
          记住
        </Button>
      </div>
      {saved.length > 0 && (
        <ul className="mt-3 space-y-1">
          {saved.map((s) => (
            <li key={s.key} className="rounded-md bg-ink-800 px-2 py-1.5 text-xs text-slate-400">
              <span className="font-medium text-slate-200">{s.key}</span>：{s.value}
            </li>
          ))}
        </ul>
      )}
    </section>
  );
}
