import { useEffect, useState } from "react";
import { queryMemory, deleteMemory } from "../lib/memoryEngine";
import Head from "next/head";

export default function ConsolePage() {
  const [memories, setMemories] = useState<any[]>([]);
  const [filter, setFilter] = useState("");
  const [activeType, setActiveType] = useState("all");
  const [activeTag, setActiveTag] = useState("");

  useEffect(() => {
    queryMemory("tyler001", "recallbricks-test")
      .then((res) => {
        console.log("📦 Loaded memories:", res);
        if (!Array.isArray(res)) return;

        const sorted = res.sort(
          (a, b) =>
            new Date(b.timestamp || "").getTime() -
            new Date(a.timestamp || "").getTime()
        );

        setMemories(sorted);
      })
      .catch((err) => {
        console.error("🔥 queryMemory failed:", err);
      });
  }, []);

  const handleDelete = async (id: string) => {
    await deleteMemory(id);
    setMemories(memories.filter((m) => m.id !== id));
  };

  const memoryTypes = Array.from(new Set(memories.map((m) => m.type))).filter(Boolean);
  const memoryTags = Array.from(
    new Set(memories.flatMap((m) => Array.isArray(m.tags) ? m.tags : []))
  ).filter(Boolean);

  const filtered = memories.filter((m) => {
    const matchesSearch = m.text?.toLowerCase().includes(filter.toLowerCase());
    const matchesType = activeType === "all" || m.type === activeType;
    const matchesTag = !activeTag || m.tags?.includes(activeTag);
    return matchesSearch && matchesType && matchesTag;
  });

  return (
    <>
      <Head>
        <title>RecallBricks Console</title>
      </Head>

      <div style={{ padding: "2rem", fontFamily: "sans-serif" }}>
        <h1 style={{ fontSize: "2rem", fontWeight: "bold" }}>🧱 RecallBricks Console</h1>
        <p>
          Viewing memory for <strong>tyler001</strong> in project{" "}
          <strong>recallbricks-test</strong>
        </p>

        <input
          type="text"
          placeholder="Search memory..."
          value={filter}
          onChange={(e) => setFilter(e.target.value)}
          style={{
            padding: "0.5rem",
            marginTop: "1rem",
            marginBottom: "1rem",
            width: "100%",
            fontSize: "1rem",
          }}
        />

        <div style={{ marginBottom: "1rem" }}>
          <label style={{ marginRight: "0.5rem" }}>Filter by Type:</label>
          <select
            value={activeType}
            onChange={(e) => setActiveType(e.target.value)}
            style={{ padding: "0.4rem" }}
          >
            <option value="all">All</option>
            {memoryTypes.map((type) => (
              <option key={type} value={type}>
                {type}
              </option>
            ))}
          </select>
        </div>

        <div
          style={{
            marginBottom: "1.5rem",
            display: "flex",
            gap: "0.5rem",
            flexWrap: "wrap",
          }}
        >
          {memoryTags.map((tag) => (
            <button
              key={tag}
              onClick={() => setActiveTag(activeTag === tag ? "" : tag)}
              style={{
                padding: "0.3rem 0.7rem",
                borderRadius: "999px",
                border: "1px solid #00aaff",
                background: activeTag === tag ? "#00aaff" : "#f0faff",
                color: activeTag === tag ? "#fff" : "#0077aa",
                cursor: "pointer",
              }}
            >
              #{tag}
            </button>
          ))}
          {activeTag && (
            <button
              onClick={() => setActiveTag("")}
              style={{
                marginLeft: "0.5rem",
                fontSize: "0.9rem",
                background: "none",
                border: "none",
                color: "#888",
                cursor: "pointer",
              }}
            >
              ✖ Clear tag
            </button>
          )}
        </div>

        <button
          onClick={() => {
            const json = JSON.stringify(filtered, null, 2);
            const blob = new Blob([json], { type: "application/json" });
            const url = URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url;
            a.download = `recallbricks-memory-${Date.now()}.json`;
            a.click();
            URL.revokeObjectURL(url);
          }}
          style={{
            padding: "0.5rem 1rem",
            fontSize: "0.9rem",
            background: "#0077ff",
            color: "white",
            border: "none",
            borderRadius: "6px",
            marginBottom: "1rem",
            cursor: "pointer",
          }}
        >
          ⬇ Export to JSON
        </button>

        <table
          style={{
            width: "100%",
            borderCollapse: "collapse",
            fontSize: "0.95rem",
            background: "#fff",
            boxShadow: "0 0 10px rgba(0,0,0,0.05)",
          }}
        >
          <thead style={{ background: "#f5f5f5" }}>
            <tr>
              <th style={{ textAlign: "left", padding: "0.5rem" }}>Text</th>
              <th style={{ textAlign: "left", padding: "0.5rem" }}>Type</th>
              <th style={{ textAlign: "left", padding: "0.5rem" }}>Tags</th>
              <th style={{ textAlign: "left", padding: "0.5rem" }}>Timestamp</th>
              <th style={{ padding: "0.5rem" }}>Delete</th>
            </tr>
          </thead>
          <tbody>
            {filtered.length === 0 ? (
              <tr>
                <td
                  colSpan={5}
                  style={{ padding: "1rem", textAlign: "center", color: "#999" }}
                >
                  No memories found.
                </td>
              </tr>
            ) : (
              filtered.map((m) => (
                <tr key={m.id || m.timestamp} style={{ borderBottom: "1px solid #eee" }}>
                  <td style={{ padding: "0.5rem" }}>{m.text || <i>(No text)</i>}</td>
                  <td style={{ padding: "0.5rem" }}>{m.type || <i>—</i>}</td>
                  <td style={{ padding: "0.5rem" }}>
                    {Array.isArray(m.tags) ? m.tags.join(", ") : <i>—</i>}
                  </td>
                  <td style={{ padding: "0.5rem" }}>
                    {m.timestamp ? new Date(m.timestamp).toLocaleString() : "—"}
                  </td>
                  <td style={{ textAlign: "center", padding: "0.5rem" }}>
                    <button
                      onClick={() => handleDelete(m.id)}
                      style={{
                        background: "none",
                        border: "none",
                        cursor: "pointer",
                        fontSize: "1.2rem",
                      }}
                      title="Delete"
                    >
                      🗑️
                    </button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </>
  );
}
