"use client";

import Link from "next/link";
import { Brain } from "lucide-react";
import { useMemory } from "@/lib/hooks";

function UsageBar({ label, usage }: { label: string; usage: string }) {
  // usage format: "42% — 939/2,200 chars"
  const pctMatch = usage.match(/(\d+)%/);
  const pct = pctMatch ? parseInt(pctMatch[1]) : 0;
  const color =
    pct > 85 ? "#ef4444" : pct > 65 ? "#f59e0b" : "#38bdf8";

  return (
    <div>
      <div className="flex justify-between text-[10px] mb-1">
        <span className="text-zinc-400">{label}</span>
        <span className="text-zinc-500 font-mono">{usage}</span>
      </div>
      <div className="h-1.5 rounded-full bg-white/[0.06]">
        <div
          className="h-full rounded-full transition-all"
          style={{ width: `${pct}%`, background: color }}
        />
      </div>
    </div>
  );
}

export function MemorySnapshotCard() {
  const { data } = useMemory();

  const memoryTarget = data?.targets?.find((t) => t.target === "memory");
  const userTarget = data?.targets?.find((t) => t.target === "user");

  return (
    <Link href="/memory">
      <div className="glass glass-hover p-4 transition-all">
        <div className="flex items-center gap-2 mb-3">
          <Brain size={16} style={{ color: "#38bdf8" }} />
          <span className="text-sm font-medium text-zinc-200">Memory</span>
          <span className="text-xs text-zinc-500 ml-auto">
            {(memoryTarget?.entry_count || 0) + (userTarget?.entry_count || 0)} entries
          </span>
        </div>
        <div className="space-y-2">
          {memoryTarget && (
            <UsageBar label="Agent" usage={memoryTarget.usage} />
          )}
          {userTarget && (
            <UsageBar label="User" usage={userTarget.usage} />
          )}
        </div>
      </div>
    </Link>
  );
}
