"use client";

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

const TAB_IDS = ["memory", "user"] 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 { toast } = useToast();

  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 handleAdd = () => {
    if (!newText.trim()) return;
    addMutation.mutate({ target: tab, content: newText.trim() }, {
      onSuccess: () => { setNewText(""); setAdding(false); toast("Entry added"); },
      onError: () => toast("Failed to add entry", "error"),
    });
  };

  const handlePatch = (oldText: string, newContent: string) => {
    patchMutation.mutate({ target: tab, old_text: oldText, content: newContent }, {
      onSuccess: () => toast("Entry updated"),
      onError: () => toast("Failed to update", "error"),
    });
  };

  const handleDelete = (oldText: string) => {
    deleteMutation.mutate({ target: tab, old_text: oldText }, {
      onSuccess: () => toast("Entry deleted"),
      onError: () => toast("Failed to delete", "error"),
    });
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold" style={{ color: "var(--text-1)" }}>Memory</h1>
        <button
          onClick={() => setAdding(!adding)}
          className="p-2 rounded-xl active:scale-95 transition-all"
          style={{ background: "var(--accent-dim)", color: "var(--accent)" }}
        >
          <Plus size={18} />
        </button>
      </div>

      <div className="flex gap-1 p-1 rounded-xl" style={{ background: "var(--bg-raised)" }}>
        {TAB_IDS.map((id) => {
          const t = data?.targets?.find((x) => x.target === id);
          const label = id === "memory" ? "Agent" : "User";
          return (
            <button
              key={id}
              onClick={() => setTab(id)}
              className="flex-1 py-2 rounded-lg text-sm font-medium transition-all flex items-center justify-center gap-1.5"
              style={{
                background: tab === id ? "var(--bg-hover)" : "transparent",
                color: tab === id ? "var(--text-1)" : "var(--text-3)",
              }}
            >
              {label}
              {t && (
                <span className="text-[10px] opacity-50">{t.entry_count}</span>
              )}
            </button>
          );
        })}
      </div>

      {usage && (
        <div className="flex items-center gap-3">
          <div className="flex-1 h-1.5 rounded-full" style={{ background: "var(--border)" }}>
            <div
              className="h-full rounded-full transition-all"
              style={{ width: pct + "%", background: pct > 85 ? "#ff3b30" : "var(--accent)" }}
            />
          </div>
          <span className="text-[11px] font-mono" style={{ color: "var(--text-3)" }}>{usage}</span>
        </div>
      )}

      {adding && (
        <div className="card p-3 space-y-2">
          <textarea
            value={newText}
            onChange={(e) => setNewText(e.target.value)}
            placeholder="New entry..."
            className="w-full bg-transparent text-sm placeholder-[var(--text-3)] resize-none outline-none min-h-[80px]"
            style={{ color: "var(--text-1)" }}
            autoFocus
          />
          <div className="flex gap-2 justify-end">
            <button onClick={() => { setAdding(false); setNewText(""); }} className="px-3 py-1.5 text-xs rounded-lg" style={{ color: "var(--text-3)" }}>
              Cancel
            </button>
            <button
              onClick={handleAdd}
              disabled={!newText.trim() || addMutation.isPending}
              className="btn-accent text-xs !py-1.5 !px-3"
            >
              {addMutation.isPending ? "Saving..." : "Add"}
            </button>
          </div>
        </div>
      )}

      {isLoading ? (
        <div className="space-y-2">
          {[...Array(3)].map((_, i) => (
            <div key={i} className="card p-4 animate-pulse">
              <div className="h-4 rounded w-full mb-2" style={{ background: "var(--bg-hover)" }} />
              <div className="h-4 rounded w-2/3" style={{ background: "var(--bg-hover)" }} />
            </div>
          ))}
        </div>
      ) : entries.length === 0 ? (
        <p className="text-sm py-8 text-center" style={{ color: "var(--text-3)" }}>No entries yet</p>
      ) : (
        <div className="space-y-2">
          {entries.map((entry, i) => (
            <MemoryEntry
              key={tab + "-" + i}
              content={entry}
              onPatch={(nc) => handlePatch(entry.slice(0, 40), nc)}
              onDelete={() => handleDelete(entry.slice(0, 40))}
            />
          ))}
        </div>
      )}
    </div>
  );
}
