import { useCallback, useEffect, useState } from "react";
import { Trash2, RefreshCw, Save, X, Pencil, Brain } from "lucide-react";
import { MemoryPanel } from "../panels/MemoryPanel";
import { listMemory, setMemory, deleteMemory, type Identity, type MemoryItem } from "../lib/api";
import { Textarea, EmptyState, useToast, cn } from "../ui";

// 记忆模块：左侧登记偏好；右侧"模型记得我什么"——按 Score 排序列出，可改/删（软删）。
export function MemoryView({ identity }: { identity: Identity }) {
  const toast = useToast();
  const [items, setItems] = useState<MemoryItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [editKey, setEditKey] = useState<string | null>(null);
  const [draft, setDraft] = useState("");

  const load = useCallback(async () => {
    setLoading(true);
    try {
      setItems(await listMemory(identity));
    } catch {
      setItems([]);
    } finally {
      setLoading(false);
    }
  }, [identity]);
  useEffect(() => {
    void load();
  }, [load]);

  const saveEdit = async (key: string) => {
    if (!draft.trim()) return;
    try {
      await setMemory(identity, key, draft.trim());
      setEditKey(null);
      toast.push("success", "已更新");
      void load();
    } catch (e) {
      toast.push("error", (e as Error).message);
    }
  };

  const remove = async (key: string) => {
    try {
      await deleteMemory(identity, key);
      toast.push("success", `已删除「${key}」`);
      void load();
    } catch (e) {
      toast.push("error", (e as Error).message);
    }
  };

  const fmtDate = (s: string) => {
    const d = new Date(s);
    return isNaN(d.getTime()) || d.getFullYear() < 2000 ? "—" : d.toLocaleDateString();
  };

  return (
    <div className="flex h-full min-h-0">
      <div className="w-96 shrink-0 overflow-y-auto border-r border-line bg-ink-900">
        <MemoryPanel identity={identity} onSaved={load} />
      </div>
      <div className="min-h-0 flex-1 overflow-y-auto p-5">
        <div className="mb-3 flex items-center gap-2">
          <Brain className="h-4 w-4 text-brand-400" />
          <h2 className="text-sm font-semibold text-slate-200">模型记得我什么（{items.length}）</h2>
          <span className="text-[11px] text-slate-600">按重要度 × 最近性排序</span>
          <button onClick={load} className="ml-auto text-slate-600 hover:text-slate-300" title="刷新">
            <RefreshCw className={cn("h-3.5 w-3.5", loading && "animate-spin")} />
          </button>
        </div>

        {items.length === 0 ? (
          <EmptyState icon={Brain} title="还没有长期记忆" desc="左侧登记偏好，或多聊几轮后系统会自动提炼（每 3 轮对账一次）。" />
        ) : (
          <ul className="space-y-2">
            {items.map((m) => (
              <li key={m.key} className="rounded-lg border border-line bg-ink-850 p-3">
                <div className="flex items-center gap-2">
                  <span className="text-sm font-medium text-slate-200">{m.key}</span>
                  <span className="rounded bg-brand/15 px-1.5 py-0.5 text-[10px] text-brand-400" title="重要度">
                    重要度 {m.importance || "—"}
                  </span>
                  <span className="text-[10px] text-slate-600">最近 {fmtDate(m.last_seen)}</span>
                  <div className="ml-auto flex items-center gap-1">
                    {editKey === m.key ? (
                      <>
                        <button onClick={() => saveEdit(m.key)} className="text-success hover:opacity-80" title="保存">
                          <Save className="h-3.5 w-3.5" />
                        </button>
                        <button onClick={() => setEditKey(null)} className="text-slate-500 hover:text-slate-300" title="取消">
                          <X className="h-3.5 w-3.5" />
                        </button>
                      </>
                    ) : (
                      <>
                        <button
                          onClick={() => {
                            setEditKey(m.key);
                            setDraft(m.value);
                          }}
                          className="text-slate-500 hover:text-brand-400"
                          title="编辑"
                        >
                          <Pencil className="h-3.5 w-3.5" />
                        </button>
                        <button onClick={() => remove(m.key)} className="text-slate-600 hover:text-danger" title="删除（软删）">
                          <Trash2 className="h-3.5 w-3.5" />
                        </button>
                      </>
                    )}
                  </div>
                </div>
                {editKey === m.key ? (
                  <Textarea className="mt-2 h-16 w-full resize-none text-xs" value={draft} onChange={(e) => setDraft(e.target.value)} autoFocus />
                ) : (
                  <div className="mt-1 text-xs text-slate-400">{m.value}</div>
                )}
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}
