import React, { useEffect, useMemo, useState } from "react";
import logo from "../assets/logo_image.png";

export default function TopBar({
  onOpenAI,
  onRefresh,
  lastUpdated,
  onEnvChange,
  selectedEnv: selectedEnvProp, // optional (ако сакаш да го контролира App)
  me,
  onLoggedOut, // optional callback (App loadMe)

  // NEW: process history switch (controlled by App)
  saveProcHistory = false,
  onToggleProcHistory, // (enabled:boolean) => void
}) {
  const [open, setOpen] = useState(false);

  // env + tokens
  const [envs, setEnvs] = useState(["default"]);
  const [selectedEnv, setSelectedEnv] = useState(selectedEnvProp || "default");
  const [newEnvName, setNewEnvName] = useState("");
  const [token, setToken] = useState("");

  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");

  const isAdmin = (me?.role || "").toLowerCase() === "admin";

  // keep in sync ако App праќа selectedEnv prop
  useEffect(() => {
    if (selectedEnvProp && selectedEnvProp !== selectedEnv) {
      setSelectedEnv(selectedEnvProp);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedEnvProp]);

  async function loadEnvironments() {
    const r = await fetch("/api/admin/environments", {
      credentials: "include",
    });
    const data = await r.json();
    if (!r.ok) throw new Error(data?.error || `HTTP ${r.status}`);

    const list = data.environments?.length ? data.environments : ["default"];
    setEnvs(list);

    if (!list.includes(selectedEnv)) {
      setSelectedEnv(list[0]);
      onEnvChange?.(list[0]);
    }
  }

  async function createEnvironment() {
    setError("");
    setToken("");

    if (!newEnvName.trim()) {
      setError("Внеси име за environment.");
      return;
    }

    setBusy(true);
    try {
      const r = await fetch("/api/admin/environments", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ name: newEnvName.trim() }),
      });

      const data = await r.json();
      if (!r.ok) throw new Error(data?.error || `HTTP ${r.status}`);

      await loadEnvironments();
      setSelectedEnv(newEnvName.trim());
      onEnvChange?.(newEnvName.trim());
      setNewEnvName("");
    } catch (e) {
      setError(String(e.message || e));
    } finally {
      setBusy(false);
    }
  }

  async function generateToken() {
    setError("");
    setToken("");
    if (!selectedEnv) {
      setError("Избери environment.");
      return;
    }

    setBusy(true);
    try {
      const r = await fetch("/api/admin/tokens", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ env: selectedEnv }),
      });

      const data = await r.json();
      if (!r.ok) throw new Error(data?.error || `HTTP ${r.status}`);

      setToken(data.token || "");
    } catch (e) {
      setError(String(e.message || e));
    } finally {
      setBusy(false);
    }
  }

  async function copyToken() {
    if (!token) return;
    await navigator.clipboard.writeText(token);
  }

  function changeEnv(val) {
    setSelectedEnv(val);
    setToken("");
    onEnvChange?.(val);
  }

  async function logout() {
    try {
      await fetch("/api/auth/logout", { method: "POST", credentials: "include" });
    } catch {}
    onLoggedOut?.();
    // reset local admin modal state
    setOpen(false);
    setToken("");
    setError("");
  }

  const prettyTime = useMemo(() => {
    if (!lastUpdated) return "Loading…";
    try {
      return `Updated ${new Date(lastUpdated).toLocaleTimeString()}`;
    } catch {
      return "Updated";
    }
  }, [lastUpdated]);

  return (
    <>
      <style>{`
        .tb-wrap{ position: sticky; top: 0; z-index: 20; backdrop-filter: blur(10px);
          background: linear-gradient(180deg, rgba(10,16,32,0.92), rgba(10,16,32,0.75));
          border-bottom: 1px solid rgba(96,165,250,0.18); }
        .tb-inner{ max-width: 1200px; margin: 0 auto; padding: 14px 18px;
          display: flex; align-items: center; justify-content: space-between; gap: 14px; }
        .tb-actions{ display:flex; align-items:center; gap: 10px; flex-wrap: wrap; justify-content: flex-end; }
        .tb-pill{ display:inline-flex; align-items:center; gap: 8px; padding: 8px 12px; border-radius: 999px;
          background: rgba(30,41,59,0.65); border: 1px solid rgba(96,165,250,0.22);
          color: rgba(255,255,255,0.9); font-weight: 800; font-size: 12px; box-shadow: inset 0 1px 0 rgba(255,255,255,0.06); }
        .tb-pill .dot{ width: 8px; height: 8px; border-radius: 999px; background: rgba(96,165,250,0.95);
          box-shadow: 0 0 0 3px rgba(96,165,250,0.15); }
        .tb-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.9); padding: 9px 12px; border-radius: 12px; font-weight: 800;
          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); }
        .tb-btn:hover{ transform: translateY(-1px); background: rgba(30,41,59,0.65); border-color: rgba(96,165,250,0.38); }
        .tb-btn:disabled{ opacity: .6; cursor: not-allowed; transform: none; }
        .tb-btn.primary{ background: linear-gradient(135deg, rgba(37,99,235,0.95), rgba(56,189,248,0.7));
          border-color: rgba(147,197,253,0.35); color: rgba(5,12,24,0.95); }
        .tb-btn.primary:hover{ background: linear-gradient(135deg, rgba(59,130,246,0.95), rgba(34,211,238,0.75)); }

        .tb-switch{ display:flex; align-items:center; gap:10px; padding: 8px 12px; border-radius: 999px;
          background: rgba(15,23,42,0.55); border: 1px solid rgba(96,165,250,0.22);
          color: rgba(255,255,255,0.9); font-weight: 800; font-size: 12px; }
        .tb-switch .label{ color: rgba(191,219,254,0.9); }
        .tb-toggle{ width: 46px; height: 26px; border-radius: 999px; position: relative; border: 1px solid rgba(96,165,250,0.25);
          background: rgba(30,41,59,0.65); cursor: pointer; transition: background .12s ease, opacity .12s ease; }
        .tb-toggle.disabled{ opacity: .55; cursor: not-allowed; }
        .tb-knob{ width: 22px; height: 22px; border-radius: 999px; position: absolute; top: 1px; left: 1px;
          background: rgba(226,232,240,0.95); transition: transform .14s ease; box-shadow: 0 6px 14px rgba(0,0,0,0.22); }
        .tb-toggle.on{ background: rgba(37,99,235,0.85); border-color: rgba(147,197,253,0.45); }
        .tb-toggle.on .tb-knob{ transform: translateX(20px); }

        .tb-backdrop{ position: fixed; inset: 0; background: rgba(2,6,23,0.72); backdrop-filter: blur(6px);
          display:flex; align-items: center; justify-content: center; padding: 20px; z-index: 50; }
        .tb-modal{ width: min(860px, 96vw); 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.22); box-shadow: 0 30px 80px rgba(0,0,0,0.45); overflow: hidden; }
        .tb-modal-head{ padding: 16px 18px; display:flex; align-items: center; justify-content: space-between; gap: 10px;
          border-bottom: 1px solid rgba(96,165,250,0.18); }
        .tb-modal-title{ color: rgba(255,255,255,0.96); font-weight: 900; letter-spacing: .3px; }
        .tb-modal-sub{ color: rgba(191,219,254,0.8); font-size: 12px; margin-top: 2px; }
        .tb-grid{ padding: 16px; display:grid; gap: 12px; }
        .tb-card{ border-radius: 16px; background: rgba(15,23,42,0.55); border: 1px solid rgba(96,165,250,0.18); padding: 14px; }
        .tb-card-head{ display:flex; align-items:center; justify-content: space-between; margin-bottom: 10px; gap: 10px; }
        .tb-card-title{ color: rgba(255,255,255,0.92); font-weight: 900; }
        .tb-help{ color: rgba(148,163,184,0.95); font-size: 12px; margin-top: 8px; line-height: 1.35; }
        .tb-input, .tb-select{ width: 100%; padding: 10px 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: 700; }
        .tb-input::placeholder{ color: rgba(148,163,184,0.75); }
        .tb-row{ display:grid; gap: 10px; }
        .tb-token{ display:flex; align-items:center; justify-content: space-between; gap: 10px; padding: 10px 12px;
          border-radius: 14px; background: rgba(2,6,23,0.38); border: 1px dashed rgba(147,197,253,0.32);
          color: rgba(255,255,255,0.92); }
        .tb-mono{ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
          font-weight: 800; color: rgba(191,219,254,0.95); }
        .tb-error{ border-color: rgba(239,68,68,0.45) !important; background: rgba(127,29,29,0.15) !important;
          color: rgba(254,202,202,0.95); }
      `}</style>

      <div className="tb-wrap">
        <div className="tb-inner">
          <div>
            <img
              src={logo}
              alt="NETIntel logo"
              className="netintel-logo"
              width={150}
              style={{ marginTop: 10 }}
            />
            <div style={{ marginTop: 4, fontSize: 12, color: "rgba(191,219,254,0.8)", fontWeight: 800 }}>
              <span style={{ color: "rgba(96,165,250,0.95)" }}>{prettyTime}</span>
              {me?.email ? (
                <span style={{ marginLeft: 10 }}>
                  • {me.email}
                  {me?.role ? ` • ${me.role}` : ""}
                </span>
              ) : null}
            </div>
          </div>

          <div className="tb-actions">
            <span className="tb-pill" title="Selected environment">
              <span className="dot" />
              Env: {selectedEnv}
            </span>

            {/* NEW: Save process history switch */}
            <div className="tb-switch" title={isAdmin ? "Toggle saving process history for this environment" : "Only admin can change this"}>
              <span className="label">Proc history</span>
              <div
                className={[
                  "tb-toggle",
                  saveProcHistory ? "on" : "",
                  !isAdmin ? "disabled" : "",
                ].join(" ")}
                role="switch"
                aria-checked={saveProcHistory ? "true" : "false"}
                tabIndex={0}
                onClick={() => {
                  if (!isAdmin) return;
                  onToggleProcHistory?.(!saveProcHistory);
                }}
                onKeyDown={(e) => {
                  if (!isAdmin) return;
                  if (e.key === "Enter" || e.key === " ") {
                    e.preventDefault();
                    onToggleProcHistory?.(!saveProcHistory);
                  }
                }}
              >
                <div className="tb-knob" />
              </div>
            </div>

            <button className="tb-btn" onClick={onRefresh} disabled={busy}>
              Refresh
            </button>

            <button
              className="tb-btn"
              onClick={async () => {
                setOpen(true);
                setError("");
                setToken("");
                try {
                  await loadEnvironments();
                } catch (e) {
                  setError(String(e.message || e));
                }
              }}
            >
              Admin
            </button>

            <button className="tb-btn primary" onClick={onOpenAI}>
              AI Assistant
            </button>
          </div>
        </div>
      </div>

      {open && (
        <div className="tb-backdrop" onMouseDown={() => setOpen(false)}>
          <div className="tb-modal" onMouseDown={(e) => e.stopPropagation()}>
            <div className="tb-modal-head">
              <div>
                <div className="tb-modal-title">Tenant Admin</div>
                <div className="tb-modal-sub">
                  Environments ➜ Generate token (clients send X-Env-Token to /receive)
                </div>
              </div>
              <div style={{ display: "flex", gap: 10 }}>
                <button className="tb-btn" onClick={logout}>
                  Logout
                </button>
                <button className="tb-btn" onClick={() => setOpen(false)}>
                  Close
                </button>
              </div>
            </div>

            <div className="tb-grid">
              <div className="tb-card">
                <div className="tb-card-head">
                  <div className="tb-card-title">Choose environment</div>
                </div>
                <div className="tb-row">
                  <select
                    className="tb-select"
                    value={selectedEnv}
                    onChange={(e) => changeEnv(e.target.value)}
                  >
                    {envs.map((e) => (
                      <option key={e} value={e}>
                        {e}
                      </option>
                    ))}
                  </select>
                  <div className="tb-help">
                    Овој env ќе се користи за dashboard филтрирање + token generation.
                    <br />
                    <b>Proc history</b> switch горе важи за тековниот env.
                  </div>
                </div>
              </div>

              <div className="tb-card">
                <div className="tb-card-head">
                  <div className="tb-card-title">Create new environment</div>
                </div>
                <div className="tb-row">
                  <input
                    className="tb-input"
                    value={newEnvName}
                    onChange={(e) => setNewEnvName(e.target.value)}
                    placeholder="e.g. school-lab / staging"
                  />
                  <button className="tb-btn" onClick={createEnvironment} disabled={busy}>
                    {busy ? "Creating…" : "Create"}
                  </button>
                </div>
              </div>

              <div className="tb-card">
                <div className="tb-card-head">
                  <div className="tb-card-title">Generate token (for clients)</div>
                </div>

                <div className="tb-row">
                  <button className="tb-btn primary" onClick={generateToken} disabled={busy}>
                    {busy ? "Generating…" : `Generate token for "${selectedEnv}"`}
                  </button>

                  {token && (
                    <>
                      <div className="tb-token">
                        <div>
                          <div style={{ fontWeight: 900, color: "rgba(255,255,255,0.92)" }}>
                            Token
                          </div>
                          <div className="tb-mono">
                            {token.slice(0, 12)}…{token.slice(-10)}
                          </div>
                        </div>
                        <button className="tb-btn" onClick={copyToken}>
                          Copy
                        </button>
                      </div>

                      <div className="tb-help">
                        Клиентот мора да праќа header: <b>X-Env-Token</b> со овој token на <b>/receive</b>.
                      </div>
                    </>
                  )}
                </div>
              </div>

              {error && (
                <div className="tb-card tb-error">
                  <div style={{ fontWeight: 900 }}>Error</div>
                  <div style={{ marginTop: 6 }}>{error}</div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}
