"use client";

import { useState } from "react";
import { Brain, Plus } from "lucide-react";
import { useMemory, useAddMemory, usePatchMemory, useDeleteMemory } from "@/lib/hooks";
import { MemoryEntry } from "@/components/MemoryEntry";

const TABS = [
  { id: "memory", label: "Agent", color: "#f59e0b" },
  { id: "user", label: "User", color: "#38bdf8" },
] as const;

export default function MemoryPage() {
  const [tab, setTab] = useState<"memory" | "user">("memory");
  const [adding, setAdding] = useState(false);
  const [newText, setNewText] = useState("");
  const { data, isLoading } = useMemory();
  const addMutation = useAddMemory();
  const patchMutation = usePatchMemory();
  const deleteMutation = useDeleteMemory();

  const target = data?.targets?.find((t) => t.target === tab);
  const entries = target?.entries || [];
  const usage = target?.usage || "";

  const pctMatch = usage.match(/(\d+)%/);
  const pct = pctMatch ? parseInt(pctMatch[1]) : 0;
  const barColor = pct > 85 ? "#ef4444" : pct > 65 ? "#f59e0b" : "#38bdf8";

  const handleAdd = () => {
    if (!newText.trim()) return;
    addMutation.mutate({ target: tab, content: newText.trim() }, {
      onSuccess: () => { setNewText(""); setAdding(false); },
    });
  };

  const handlePatch = (oldText: string, newContent: string) => {
    patchMutation.mutate({ target: tab, old_text: oldText, content: newContent });
  };

  const handleDelete = (oldText: string) => {
    deleteMutation.mutate({ target: tab, old_text: oldText });
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Brain size={20} style={{ color: "#38bdf8" }} />
          <h1 className="text-xl font-bold" style={{ color: "#38bdf8" }}>Memory</h1>
        </div>
        <button
          onClick={() => setAdding(!adding)}
          className="p-2 rounded-xl transition-all active:scale-95"
          style={{ background: "rgba(56,189,248,0.15)", color: "#38bdf8" }}
        >
          <Plus size={18} />
        </button>
      </div>

      {/* Tabs */}
      <div className="flex gap-2">
        {TABS.map((t) => (
          <button
            key={t.id}
            onClick={() => setTab(t.id)}
            className="flex-1 py-2 rounded-xl text-sm font-medium transition-all"
            style={{
              background: tab === t.id ? `${t.color}20` : "rgba(255,255,255,0.04)",
              color: tab === t.id ? t.color : "#6b7280",
              border: `1px solid ${tab === t.id ? `${t.color}40` : "rgba(255,255,255,0.06)"}`,
            }}
          >
            {t.label}
          </button>
        ))}
      </div>

      {/* Usage bar */}
      {usage && (
        <div>
          <div className="flex justify-between text-xs mb-1">
            <span className="text-zinc-400">{tab === "memory" ? "Agent memory" : "User profile"}</span>
            <span className="text-zinc-500 font-mono">{usage}</span>
          </div>
          <div className="h-2 rounded-full bg-white/[0.06]">
            <div
              className="h-full rounded-full transition-all"
              style={{ width: `${pct}%`, background: barColor }}
            />
          </div>
        </div>
      )}

      {/* Add form */}
      {adding && (
        <div className="glass p-3 space-y-2">
          <textarea
            value={newText}
            onChange={(e) => setNewText(e.target.value)}
            placeholder="New memory entry..."
            className="w-full bg-transparent text-sm text-zinc-200 placeholder-zinc-600 resize-none outline-none min-h-[80px]"
            autoFocus
          />
          <div className="flex gap-2 justify-end">
            <button
              onClick={() => { setAdding(false); setNewText(""); }}
              className="px-3 py-1.5 text-xs text-zinc-400 rounded-lg"
            >
              Cancel
            </button>
            <button
              onClick={handleAdd}
              disabled={!newText.trim() || addMutation.isPending}
              className="px-3 py-1.5 text-xs rounded-lg font-medium disabled:opacity-40"
              style={{ background: "rgba(56,189,248,0.2)", color: "#38bdf8" }}
            >
              {addMutation.isPending ? "Saving..." : "Add"}
            </button>
          </div>
        </div>
      )}

      {/* Entries */}
      {isLoading ? (
        <div className="space-y-2">
          {[...Array(3)].map((_, i) => (
            <div key={i} className="glass p-4 animate-pulse">
              <div className="h-4 bg-white/[0.06] rounded w-full mb-2" />
              <div className="h-4 bg-white/[0.06] rounded w-2/3" />
            </div>
          ))}
        </div>
      ) : entries.length === 0 ? (
        <div className="glass p-6 text-center text-sm text-zinc-500">
          No entries yet
        </div>
      ) : (
        <div className="space-y-2">
          {entries.map((entry, i) => (
            <MemoryEntry
              key={`${tab}-${i}`}
              content={entry}
              onPatch={(newContent) => handlePatch(entry.slice(0, 40), newContent)}
              onDelete={() => handleDelete(entry.slice(0, 40))}
            />
          ))}
        </div>
      )}
    </div>
  );
}
