import { useEffect, useMemo, useState } from "react";
import {
  activateProtection,
  cancelRelease,
  logout,
  requestRelease,
  UiState,
} from "../lib/ipc";
import appIcon from "../assets/app-icon.png";

interface Props {
  state: UiState;
  onState: (s: UiState) => void;
}

function useCountdown(targetIso: string | null): string | null {
  const target = useMemo(
    () => (targetIso ? new Date(targetIso).getTime() : null),
    [targetIso],
  );
  const [now, setNow] = useState(Date.now());

  useEffect(() => {
    if (target === null) return;
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, [target]);

  if (target === null) return null;
  const ms = Math.max(0, target - now);
  const h = Math.floor(ms / 3_600_000);
  const m = Math.floor((ms % 3_600_000) / 60_000);
  const s = Math.floor((ms % 60_000) / 1000);
  const pad = (n: number) => String(n).padStart(2, "0");
  return `${pad(h)}:${pad(m)}:${pad(s)}`;
}

export default function HubView({ state, onState }: Props) {
  const [busy, setBusy] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const countdown = useCountdown(state.releaseAvailableAt);

  const run = async (key: string, fn: () => Promise<UiState>) => {
    setBusy(key);
    setError(null);
    try {
      onState(await fn());
    } catch (e) {
      setError(String(e));
    } finally {
      setBusy(null);
    }
  };

  const cooldownActive = state.releaseRequestedAt !== null;

  return (
    <>
      <div className="header">
        <img src={appIcon} alt="" />
        <span className="wordmark">ReBreak Magic</span>
        <div className="spacer" />
        {state.plan && <span className="plan-badge">{state.plan}</span>}
        {state.nickname && <span className="nickname">{state.nickname}</span>}
      </div>

      <div className="content">
        {/* ---- Schutz-Status ---- */}
        <div className="card">
          <div className="status-row">
            <div
              className={`status-dot ${
                cooldownActive ? "cooldown" : state.protectionApplied ? "on" : "off"
              }`}
            />
            <div className="grow">
              <h2>
                {cooldownActive
                  ? "Schutz wird aufgehoben"
                  : state.protectionApplied
                    ? "Schutz aktiv"
                    : "Schutz nicht aktiv"}
              </h2>
              <p className="sub">
                {cooldownActive
                  ? "Der 24-Stunden-Cooldown läuft. Bis dahin bleibt der Schutz vollständig aktiv."
                  : state.protectionApplied
                    ? "Glücksspielseiten werden auf diesem PC systemweit über ReBreak-DNS blockiert."
                    : "Aktiviere den DNS-Schutz für diesen PC. Windows fragt dabei einmalig nach Administrator-Rechten."}
              </p>
            </div>
            {!state.protectionApplied && !cooldownActive && (
              <button
                className="btn-primary"
                disabled={busy !== null || !state.registered}
                onClick={() => run("activate", activateProtection)}
              >
                {busy === "activate" ? "Wird eingerichtet …" : "Schutz aktivieren"}
              </button>
            )}
          </div>
        </div>

        {/* ---- Cooldown ---- */}
        {cooldownActive && (
          <div className="card">
            <h2>Verbleibende Zeit</h2>
            <p className="sub">
              Danach hebt ReBreak den Schutz auf diesem PC automatisch auf.
              Du kannst es dir jederzeit anders überlegen.
            </p>
            <div className="row" style={{ marginTop: 12 }}>
              <span className="countdown">{countdown ?? "—"}</span>
              <div className="grow" />
              <button
                className="btn-secondary"
                disabled={busy !== null}
                onClick={() => run("cancel", cancelRelease)}
              >
                {busy === "cancel" ? "…" : "Schutz behalten"}
              </button>
            </div>
          </div>
        )}

        {/* ---- Gerät ---- */}
        <div className="card">
          <h2>Dieses Gerät</h2>
          <p className="sub">
            {state.hostname}
            {state.registered
              ? " — mit deinem ReBreak-Konto verbunden."
              : " — noch nicht registriert."}
          </p>
        </div>

        {error && <p className="error">{error}</p>}

        {/* ---- Aktionen ---- */}
        <div className="row end">
          {state.protectionApplied && !cooldownActive && (
            <button
              className="btn-danger-quiet"
              disabled={busy !== null}
              onClick={() => run("release", requestRelease)}
            >
              {busy === "release" ? "…" : "Schutz pausieren (24h-Cooldown)"}
            </button>
          )}
          <button
            className="btn-link"
            disabled={busy !== null}
            onClick={() => run("logout", logout)}
          >
            Abmelden
          </button>
        </div>
      </div>
    </>
  );
}
