import React, { useEffect, useMemo, useState } from "react";

function severityForEventId(eventId) {
  const id = Number.parseInt(String(eventId ?? ""), 10);
  const high = new Set([1, 3, 8, 10]);
  const med = new Set([5, 6, 7, 11, 22]);
  if (high.has(id)) return "high";
  if (med.has(id)) return "medium";
  return "low";
}

function fmtTime(ts) {
  if (!ts) return "—";
  try {
    return new Date(ts).toLocaleTimeString();
  } catch {
    return String(ts);
  }
}

export default function ComputerDetailsModal({ open, computer, onClose, onAskAI }) {
  const [tab, setTab] = useState("overview");
  const [loading, setLoading] = useState(false);
  const [details, setDetails] = useState(null);
  const [error, setError] = useState("");
  const [search, setSearch] = useState("");

  // JSON viewer
  const [jsonOpen, setJsonOpen] = useState(false);
  const [jsonTitle, setJsonTitle] = useState("");
  const [jsonData, setJsonData] = useState(null);

  // reset when opening / switching pc
  useEffect(() => {
    if (!open) return;
    setTab("overview");
    setSearch("");
    setError("");
    setDetails(null);
    setJsonOpen(false);
    setJsonTitle("");
    setJsonData(null);
  }, [open, computer?.name]);

  // close on ESC
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === "Escape") onClose?.();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  // load details
  useEffect(() => {
    if (!open || !computer?.name) return;
    let cancelled = false;

    async function load() {
      setLoading(true);
      setError("");
      try {
        const r = await fetch(`/api/computer/${encodeURIComponent(computer.name)}`, {
          credentials: "include",
        });
        const d = await r.json().catch(() => ({}));
        if (!r.ok) throw new Error(d?.error || `HTTP ${r.status}`);
        if (!cancelled) setDetails(d);
      } catch (e) {
        if (!cancelled) {
          setError(String(e?.message || e));
          setDetails(null);
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    }

    load();
    return () => {
      cancelled = true;
    };
  }, [open, computer?.name]);

  const filteredSysmon = useMemo(() => {
    const list = details?.sysmon_events || [];
    const q = search.trim().toLowerCase();
    if (!q) return list;
    return list.filter((ev) => {
      const msg = (ev.message || "").toLowerCase();
      const type = (ev.event_type || "").toLowerCase();
      const id = String(ev.event_id ?? "").toLowerCase();
      return msg.includes(q) || type.includes(q) || id.includes(q);
    });
  }, [details, search]);

  function openJson(ev) {
    setJsonTitle(`Sysmon Event ${ev?.event_id ?? ""} • ${ev?.event_type ?? ""}`);
    setJsonData(ev?.details ?? ev);
    setJsonOpen(true);
  }

  function closeJson() {
    setJsonOpen(false);
    setJsonTitle("");
    setJsonData(null);
  }

  if (!open) return null;

  return (
    <>
      <style>{`
        .cdm-backdrop{
          position: fixed; inset: 0; z-index: 60;
          background: rgba(2,6,23,0.70);
          backdrop-filter: blur(6px);
          display:flex; align-items:center; justify-content:center;
          padding: 18px;
        }
        .cdm-modal{
          width: min(1100px, 96vw);
          height: min(86vh, 860px);
          display:flex; flex-direction:column;
          border-radius: 18px;
          background: radial-gradient(900px 420px at 20% 0%, rgba(96,165,250,0.18), transparent 60%),
                      radial-gradient(700px 350px at 80% 10%, rgba(34,211,238,0.10), transparent 55%),
                      rgba(10,16,32,0.92);
          border: 1px solid rgba(96,165,250,0.20);
          box-shadow: 0 30px 80px rgba(0,0,0,0.45);
          overflow: hidden;
        }
        .cdm-head{
          padding: 14px 16px;
          border-bottom: 1px solid rgba(96,165,250,0.16);
          display:flex; align-items:center; justify-content:space-between; gap:12px;
        }
        .cdm-title{ font-size: 16px; font-weight: 900; color: rgba(255,255,255,0.95); }
        .cdm-sub{ margin-top: 2px; font-size: 12px; color: rgba(191,219,254,0.80); }
        .cdm-right{ display:flex; align-items:center; gap:10px; flex-wrap:wrap; justify-content:flex-end; }
        .cdm-tabs{
          display:flex; gap:8px; padding: 6px;
          background: rgba(15,23,42,0.45);
          border: 1px solid rgba(96,165,250,0.18);
          border-radius: 999px;
        }
        .cdm-tab{
          appearance:none; border: 0;
          padding: 8px 12px;
          border-radius: 999px;
          background: transparent;
          color: rgba(226,232,240,0.88);
          font-weight: 900;
          font-size: 12px;
          cursor:pointer;
          transition: background .12s ease, transform .12s ease, color .12s ease;
        }
        .cdm-tab:hover{ transform: translateY(-1px); background: rgba(30,41,59,0.55); }
        .cdm-tab.active{
          background: linear-gradient(135deg, rgba(37,99,235,0.95), rgba(56,189,248,0.65));
          color: rgba(5,12,24,0.95);
        }
        .cdm-btn{
          appearance:none;
          border: 1px solid rgba(96,165,250,0.22);
          background: rgba(15,23,42,0.55);
          color: rgba(255,255,255,0.92);
          padding: 9px 12px;
          border-radius: 12px;
          font-weight: 900;
          font-size: 13px;
          cursor: pointer;
          transition: transform .12s ease, background .12s ease, border-color .12s ease, opacity .12s ease;
          box-shadow: 0 8px 20px rgba(0,0,0,0.18);
        }
        .cdm-btn:hover{ transform: translateY(-1px); background: rgba(30,41,59,0.65); border-color: rgba(96,165,250,0.38); }
        .cdm-btn:disabled{ opacity: .6; cursor: not-allowed; transform:none; }
        .cdm-btn.primary{
          background: linear-gradient(135deg, rgba(37,99,235,0.95), rgba(56,189,248,0.65));
          border-color: rgba(147,197,253,0.35);
          color: rgba(5,12,24,0.95);
        }

        /* body scroll zone */
        .cdm-body{
          flex: 1;
          display:flex;
          flex-direction:column;
          min-height: 0; /* important for scroll */
        }
        .cdm-content{
          flex: 1;
          min-height: 0;
          overflow: auto;
          padding: 14px 16px 18px;
        }

        .cdm-panel{
          border-radius: 16px;
          background: rgba(15,23,42,0.55);
          border: 1px solid rgba(96,165,250,0.16);
          overflow: hidden;
        }
        .cdm-panel-head{
          padding: 12px 12px;
          display:flex; align-items:center; justify-content:space-between; gap:10px;
          border-bottom: 1px solid rgba(96,165,250,0.14);
        }
        .cdm-panel-title{ color: rgba(255,255,255,0.92); font-weight: 900; }
        .cdm-panel-body{ padding: 12px; }

        /* table area scroll fix */
        .cdm-table-wrap{
          border-radius: 14px;
          border: 1px solid rgba(148,163,184,0.18);
          background: rgba(2,6,23,0.28);
          overflow: hidden;
        }
        .cdm-table-scroll{
          max-height: 52vh;
          overflow: auto;
        }
        table{ width: 100%; border-collapse: collapse; }
        thead th{
          position: sticky; top: 0;
          background: rgba(10,16,32,0.95);
          backdrop-filter: blur(8px);
          text-align:left;
          font-size: 12px;
          color: rgba(191,219,254,0.88);
          padding: 10px 10px;
          border-bottom: 1px solid rgba(96,165,250,0.16);
          z-index: 1;
        }
        tbody td{
          padding: 10px 10px;
          border-bottom: 1px solid rgba(148,163,184,0.12);
          color: rgba(226,232,240,0.92);
          font-size: 13px;
          vertical-align: top;
        }
        tbody tr:hover td{ background: rgba(30,41,59,0.35); }

        .cdm-pill{
          display:inline-flex; align-items:center; gap:8px;
          padding: 6px 10px;
          border-radius: 999px;
          background: rgba(30,41,59,0.55);
          border: 1px solid rgba(96,165,250,0.18);
          color: rgba(255,255,255,0.9);
          font-weight: 900;
          font-size: 12px;
        }
        .cdm-input{
          width: min(420px, 45vw);
          padding: 9px 12px;
          border-radius: 12px;
          border: 1px solid rgba(96,165,250,0.18);
          background: rgba(2,6,23,0.35);
          color: rgba(255,255,255,0.92);
          outline: none;
          font-weight: 800;
        }
        .cdm-input::placeholder{ color: rgba(148,163,184,0.75); }

        .cdm-badge{
          display:inline-flex; align-items:center; justify-content:center;
          padding: 5px 10px;
          border-radius: 999px;
          font-weight: 1000;
          font-size: 11px;
          letter-spacing: .3px;
          border: 1px solid rgba(148,163,184,0.18);
          background: rgba(15,23,42,0.5);
          color: rgba(226,232,240,0.95);
        }
        .cdm-badge.high{ border-color: rgba(239,68,68,0.35); color: rgba(254,202,202,0.95); }
        .cdm-badge.medium{ border-color: rgba(251,191,36,0.35); color: rgba(254,243,199,0.95); }
        .cdm-badge.low{ border-color: rgba(34,197,94,0.25); color: rgba(220,252,231,0.95); }

        /* JSON modal */
        .cdm-json-modal{
          width: min(980px, 96vw);
          height: min(82vh, 860px);
          display:flex; flex-direction:column;
          border-radius: 18px;
          background: rgba(10,16,32,0.94);
          border: 1px solid rgba(96,165,250,0.20);
          overflow:hidden;
        }
        .cdm-json-body{
          flex:1; min-height:0; overflow:auto; padding: 14px 16px 18px;
        }
        .cdm-pre{
          margin: 0;
          padding: 14px;
          border-radius: 12px;
          border: 1px solid rgba(148,163,184,0.22);
          background: rgba(2,6,23,0.35);
          color: rgba(226,232,240,0.95);
          font-size: 12px;
          line-height: 1.5;
          white-space: pre-wrap;
          word-break: break-word;
        }
      `}</style>

      <div className="cdm-backdrop" onMouseDown={onClose}>
        <div className="cdm-modal" onMouseDown={(e) => e.stopPropagation()}>
          <div className="cdm-head">
            <div>
              <div className="cdm-title">{computer?.name || "Computer"}</div>
              <div className="cdm-sub">
                {computer?.ip || "—"} • {computer?.user || "—"} • {computer?.status || "—"}
              </div>
            </div>

            <div className="cdm-right">
              <button className="cdm-btn primary" onClick={() => onAskAI?.(computer?.name)} disabled={!computer?.name}>
                Ask AI
              </button>

              <div className="cdm-tabs">
                <button className={`cdm-tab ${tab === "overview" ? "active" : ""}`} onClick={() => setTab("overview")}>
                  Overview
                </button>
                <button className={`cdm-tab ${tab === "sysmon" ? "active" : ""}`} onClick={() => setTab("sysmon")}>
                  Sysmon
                </button>
                <button className={`cdm-tab ${tab === "processes" ? "active" : ""}`} onClick={() => setTab("processes")}>
                  Processes
                </button>
                <button className={`cdm-tab ${tab === "network" ? "active" : ""}`} onClick={() => setTab("network")}>
                  Network
                </button>
              </div>

              <button className="cdm-btn" onClick={onClose}>
                Close
              </button>
            </div>
          </div>

          <div className="cdm-body">
            <div className="cdm-content">
              {loading && <div style={{ color: "rgba(148,163,184,0.95)" }}>Loading…</div>}

              {!loading && error && (
                <div className="cdm-panel" style={{ borderColor: "rgba(239,68,68,0.35)" }}>
                  <div className="cdm-panel-head">
                    <div className="cdm-panel-title">Error</div>
                  </div>
                  <div className="cdm-panel-body" style={{ color: "rgba(254,202,202,0.95)" }}>
                    {error}
                  </div>
                </div>
              )}

              {!loading && !error && details && tab === "overview" && (
                <div className="cdm-panel">
                  <div className="cdm-panel-head">
                    <div className="cdm-panel-title">System Overview</div>
                    <span className="cdm-pill">Env: {details.computer?.env_name || "default"}</span>
                  </div>
                  <div className="cdm-panel-body" style={{ display: "grid", gap: 10 }}>
                    <div><b>User:</b> {details.computer?.user || "—"}</div>
                    <div><b>IP:</b> {details.computer?.ip || "—"}</div>
                    <div><b>OS:</b> {details.computer?.os || "—"}</div>
                    <div><b>First seen:</b> {details.computer?.first_seen || "—"}</div>
                    <div><b>Last seen:</b> {details.computer?.last_seen || "—"}</div>
                    <div><b>Total logs:</b> {details.computer?.total_logs ?? "—"}</div>
                  </div>
                </div>
              )}

              {!loading && !error && details && tab === "sysmon" && (
                <div className="cdm-panel">
                  <div className="cdm-panel-head">
                    <div className="cdm-panel-title">Sysmon Events</div>
                    <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                      <span className="cdm-pill">{filteredSysmon.length} events</span>
                      <input
                        className="cdm-input"
                        placeholder="Search by id / type / message…"
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                      />
                    </div>
                  </div>

                  <div className="cdm-panel-body">
                    <div className="cdm-table-wrap">
                      <div className="cdm-table-scroll">
                        <table>
                          <thead>
                            <tr>
                              <th style={{ width: 90 }}>Time</th>
                              <th style={{ width: 70 }}>ID</th>
                              <th style={{ width: 190 }}>Type</th>
                              <th style={{ width: 110 }}>Severity</th>
                              <th>Message</th>
                              <th style={{ width: 90 }}>View</th>
                            </tr>
                          </thead>
                          <tbody>
                            {filteredSysmon.slice(0, 400).map((ev, idx) => {
                              const sev = severityForEventId(ev.event_id);
                              return (
                                <tr key={idx}>
                                  <td>{fmtTime(ev.timestamp)}</td>
                                  <td><b>{ev.event_id ?? "—"}</b></td>
                                  <td>{ev.event_type || "—"}</td>
                                  <td><span className={`cdm-badge ${sev}`}>{sev.toUpperCase()}</span></td>
                                  <td style={{ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", fontSize: 12 }}>
                                    {(ev.message || "").slice(0, 220)}
                                  </td>
                                  <td>
                                    <button className="cdm-btn" onClick={() => openJson(ev)}>
                                      View
                                    </button>
                                  </td>
                                </tr>
                              );
                            })}

                            {filteredSysmon.length === 0 && (
                              <tr>
                                <td colSpan="6" style={{ color: "rgba(148,163,184,0.95)" }}>
                                  No sysmon events.
                                </td>
                              </tr>
                            )}
                          </tbody>
                        </table>
                      </div>
                    </div>
                    {filteredSysmon.length > 400 && (
                      <div style={{ marginTop: 10, color: "rgba(148,163,184,0.95)", fontSize: 12 }}>
                        Showing first 400 (for speed).
                      </div>
                    )}
                  </div>
                </div>
              )}

              {!loading && !error && details && tab === "processes" && (
                <div className="cdm-panel">
                  <div className="cdm-panel-head">
                    <div className="cdm-panel-title">Recent Processes</div>
                    <span className="cdm-pill">{(details.recent_processes || []).length} rows</span>
                  </div>

                  <div className="cdm-panel-body">
                    <div className="cdm-table-wrap">
                      <div className="cdm-table-scroll">
                        <table>
                          <thead>
                            <tr>
                              <th style={{ width: 90 }}>Time</th>
                              <th style={{ width: 80 }}>PID</th>
                              <th style={{ width: 200 }}>Name</th>
                              <th style={{ width: 140 }}>User</th>
                              <th style={{ width: 90 }}>CPU%</th>
                              <th style={{ width: 110 }}>RAM MB</th>
                              <th>Cmdline</th>
                            </tr>
                          </thead>
                          <tbody>
                            {(details.recent_processes || []).slice(0, 400).map((p, idx) => (
                              <tr key={idx}>
                                <td>{fmtTime(p.timestamp)}</td>
                                <td><b>{p.pid ?? "—"}</b></td>
                                <td>{p.name || "—"}</td>
                                <td>{p.username || "—"}</td>
                                <td>{p.cpu_percent ?? 0}</td>
                                <td>{p.memory_mb ?? 0}</td>
                                <td style={{ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", fontSize: 12 }}>
                                  {(p.cmdline || "").slice(0, 220)}
                                </td>
                              </tr>
                            ))}
                            {(details.recent_processes || []).length === 0 && (
                              <tr>
                                <td colSpan="7" style={{ color: "rgba(148,163,184,0.95)" }}>
                                  No process data.
                                </td>
                              </tr>
                            )}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {!loading && !error && details && tab === "network" && (
                <div className="cdm-panel">
                  <div className="cdm-panel-head">
                    <div className="cdm-panel-title">Network Connections</div>
                    <span className="cdm-pill">{(details.network_connections || []).length} rows</span>
                  </div>

                  <div className="cdm-panel-body">
                    <div className="cdm-table-wrap">
                      <div className="cdm-table-scroll">
                        <table>
                          <thead>
                            <tr>
                              <th style={{ width: 90 }}>Time</th>
                              <th style={{ width: 80 }}>PID</th>
                              <th style={{ width: 180 }}>Process</th>
                              <th style={{ width: 220 }}>Local</th>
                              <th style={{ width: 220 }}>Remote</th>
                              <th style={{ width: 140 }}>Status</th>
                            </tr>
                          </thead>
                          <tbody>
                            {(details.network_connections || []).slice(0, 400).map((n, idx) => (
                              <tr key={idx}>
                                <td>{fmtTime(n.timestamp)}</td>
                                <td><b>{n.pid ?? "—"}</b></td>
                                <td>{n.process_name || "—"}</td>
                                <td style={{ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", fontSize: 12 }}>
                                  {n.local_address || "—"}
                                </td>
                                <td style={{ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", fontSize: 12 }}>
                                  {n.remote_address || "—"}
                                </td>
                                <td>{n.status || "—"}</td>
                              </tr>
                            ))}
                            {(details.network_connections || []).length === 0 && (
                              <tr>
                                <td colSpan="6" style={{ color: "rgba(148,163,184,0.95)" }}>
                                  No network data.
                                </td>
                              </tr>
                            )}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {!loading && !error && !details && (
                <div style={{ color: "rgba(148,163,184,0.95)" }}>No details.</div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* JSON VIEWER */}
      {jsonOpen && (
        <div className="cdm-backdrop" onMouseDown={closeJson}>
          <div className="cdm-json-modal" onMouseDown={(e) => e.stopPropagation()}>
            <div className="cdm-head">
              <div>
                <div className="cdm-title">View JSON</div>
                <div className="cdm-sub">{jsonTitle}</div>
              </div>
              <div className="cdm-right">
                <button
                  className="cdm-btn"
                  onClick={() => navigator.clipboard.writeText(JSON.stringify(jsonData ?? {}, null, 2))}
                >
                  Copy
                </button>
                <button className="cdm-btn" onClick={closeJson}>
                  Close
                </button>
              </div>
            </div>

            <div className="cdm-json-body">
              <pre className="cdm-pre">{JSON.stringify(jsonData ?? {}, null, 2)}</pre>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
