import { useState, useEffect } from "react";

function formatDate(isoString) {
  try {
    return new Date(isoString).toLocaleString();
  } catch {
    return isoString;
  }
}

function LevelBadge({ line }) {
  const text = line.toUpperCase();
  if (text.includes("ERROR") || text.includes("ERR") || text.includes("[E]")) {
    return <span className="text-xs font-bold" style={{ color: "var(--danger)" }}>ERR</span>;
  }
  if (text.includes("WARN") || text.includes("[W]")) {
    return <span className="text-xs font-bold" style={{ color: "#fb923c" }}>WRN</span>;
  }
  return null;
}

function lineColor(text) {
  const t = text.toUpperCase();
  if (t.includes("ERROR") || t.includes("ERR]") || t.includes("[E]")) return "var(--danger-text)";
  if (t.includes("WARN") || t.includes("[W]")) return "#fb923c";
  return "#7ec87e";
}

export default function SerialLogViewer() {
  const [sessions, setSessions] = useState([]);
  const [expanded, setExpanded] = useState(null);
  const [search, setSearch]     = useState("");

  useEffect(() => {
    const raw = localStorage.getItem("bellsystems_serial_logs");
    if (raw) {
      try { setSessions(JSON.parse(raw)); } catch (_) {}
    }
  }, []);

  const handleDelete = (id) => {
    const updated = sessions.filter((s) => s.id !== id);
    setSessions(updated);
    localStorage.setItem("bellsystems_serial_logs", JSON.stringify(updated));
    if (expanded === id) setExpanded(null);
  };

  const handleExport = (session) => {
    const text = session.lines.map((l) => `[${l.ts}] ${l.text}`).join("\n");
    const blob = new Blob([text], { type: "text/plain" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `serial-log-${session.label}.txt`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const filteredSessions = sessions.filter((s) => {
    if (!search) return true;
    const q = search.toLowerCase();
    return (
      s.label.toLowerCase().includes(q) ||
      s.lines?.some((l) => l.text.toLowerCase().includes(q))
    );
  });

  return (
    <div>
      {/* Page header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-xl font-bold" style={{ color: "var(--text-heading)" }}>Serial Log Viewer</h1>
          <p className="text-sm mt-0.5" style={{ color: "var(--text-muted)" }}>
            Saved sessions from the Serial Monitor page.
          </p>
        </div>
        <span className="text-sm" style={{ color: "var(--text-muted)" }}>
          {sessions.length} session{sessions.length !== 1 ? "s" : ""} stored
        </span>
      </div>

      {/* Search */}
      {sessions.length > 0 && (
        <div className="mb-4">
          <input
            type="text"
            placeholder="Search sessions or log content…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full px-3 py-2 rounded-md text-sm"
            style={{
              backgroundColor: "var(--bg-card)",
              border: "1px solid var(--border-input)",
              color: "var(--text-primary)",
              outline: "none",
            }}
          />
        </div>
      )}

      {/* Empty state */}
      {sessions.length === 0 && (
        <div
          className="rounded-lg border p-10 text-center"
          style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
        >
          <svg className="w-10 h-10 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"
            style={{ color: "var(--text-muted)" }}>
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
              d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
          </svg>
          <p className="text-sm font-medium mb-1" style={{ color: "var(--text-secondary)" }}>No saved logs yet</p>
          <p className="text-xs" style={{ color: "var(--text-muted)" }}>
            Use the Serial Monitor page to connect and save sessions.
          </p>
        </div>
      )}

      {/* Session list */}
      <div className="space-y-2">
        {filteredSessions.map((session) => {
          const isOpen = expanded === session.id;

          // If searching, filter lines too
          const displayLines = search
            ? session.lines?.filter((l) => l.text.toLowerCase().includes(search.toLowerCase()))
            : session.lines;

          return (
            <div
              key={session.id}
              className="rounded-lg border overflow-hidden"
              style={{ backgroundColor: "var(--bg-card)", borderColor: isOpen ? "var(--accent)" : "var(--border-primary)" }}
            >
              {/* Session header row */}
              <button
                type="button"
                onClick={() => setExpanded(isOpen ? null : session.id)}
                className="w-full flex items-center justify-between px-4 py-3 text-left cursor-pointer hover:bg-[var(--bg-card-hover)] transition-colors"
              >
                <div className="flex items-center gap-3">
                  {/* Chevron */}
                  <svg
                    className={`w-4 h-4 flex-shrink-0 transition-transform ${isOpen ? "rotate-90" : ""}`}
                    fill="none" stroke="currentColor" viewBox="0 0 24 24"
                    style={{ color: "var(--text-muted)" }}
                  >
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>

                  {/* Icon */}
                  <svg className="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                    style={{ color: isOpen ? "var(--accent)" : "var(--text-muted)" }}>
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8}
                      d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                  </svg>

                  <div>
                    <span className="text-sm font-medium font-mono" style={{ color: "var(--text-heading)" }}>
                      {session.label}
                    </span>
                    <span className="text-xs ml-3" style={{ color: "var(--text-muted)" }}>
                      {formatDate(session.savedAt)}
                    </span>
                  </div>
                </div>

                <div className="flex items-center gap-3">
                  <span
                    className="text-xs px-2 py-0.5 rounded-full font-medium"
                    style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-muted)" }}
                  >
                    {session.lineCount} lines
                  </span>
                </div>
              </button>

              {/* Expanded log panel */}
              {isOpen && (
                <div style={{ borderTop: "1px solid var(--border-primary)" }}>
                  {/* Toolbar */}
                  <div
                    className="flex items-center justify-between px-4 py-2"
                    style={{ backgroundColor: "var(--bg-secondary)", borderBottom: "1px solid var(--border-primary)" }}
                  >
                    <span className="text-xs" style={{ color: "var(--text-muted)" }}>
                      {search ? `${displayLines?.length ?? 0} of ${session.lineCount} lines match` : `${session.lineCount} lines`}
                    </span>
                    <div className="flex items-center gap-2">
                      <button
                        onClick={() => handleExport(session)}
                        className="px-3 py-1 rounded text-xs font-medium cursor-pointer hover:opacity-80 transition-opacity flex items-center gap-1"
                        style={{ backgroundColor: "var(--bg-card-hover)", color: "var(--text-secondary)", border: "1px solid var(--border-primary)" }}
                      >
                        <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                            d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                        </svg>
                        Export .txt
                      </button>
                      <button
                        onClick={() => handleDelete(session.id)}
                        className="px-3 py-1 rounded text-xs font-medium cursor-pointer hover:opacity-80 transition-opacity"
                        style={{ backgroundColor: "var(--danger-bg)", color: "var(--danger-text)", border: "1px solid var(--danger)" }}
                      >
                        Delete
                      </button>
                    </div>
                  </div>

                  {/* Log content */}
                  <div
                    className="overflow-y-auto font-mono text-xs"
                    style={{
                      backgroundColor: "#070d07",
                      maxHeight: 500,
                      padding: "10px 14px",
                    }}
                  >
                    {(!displayLines || displayLines.length === 0) ? (
                      <span style={{ color: "#3a5c3a" }}>No lines to display.</span>
                    ) : (
                      displayLines.map((l, i) => (
                        <div key={i} className="leading-relaxed flex items-start gap-2">
                          <span className="flex-shrink-0" style={{ color: "#3a6b3a", userSelect: "none" }}>
                            {l.ts}
                          </span>
                          <span style={{ color: lineColor(l.text) }}>{l.text}</span>
                        </div>
                      ))
                    )}
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}
