"use client";

import Image from "next/image";
import { useEffect, useMemo, useState } from "react";

type HealthSummary = {
  status: string;
  version?: string;
  serviceId?: string;
  description?: string;
  checks: Record<string, { status: string; output?: string }>;
};

export default function Home() {
  const [health, setHealth] = useState<HealthSummary | null>(null);
  const [ready, setReady] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [readyError, setReadyError] = useState<string | null>(null);
  const [attemptedHealthUrl, setAttemptedHealthUrl] = useState<string | null>(
    null
  );
  const [attemptedReadyUrl, setAttemptedReadyUrl] = useState<string | null>(
    null
  );
  const [lastUpdated, setLastUpdated] = useState<string | null>(null);
  const [isPolling, setIsPolling] = useState(false);
  const [starsActive, setStarsActive] = useState(false);

  const apiBase = useMemo(
    () => process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000",
    []
  );

  useEffect(() => {
    async function fetchHealth() {
      try {
        const url = `${apiBase}/health`;
        setAttemptedHealthUrl(url);
        const res = await fetch(url);
        if (!res.ok) throw new Error(`Health check failed: ${res.status}`);
        const payload = (await res.json()) as HealthSummary;
        setHealth(payload);
        setError(null);
        return true;
      } catch (err) {
        const message = err instanceof Error ? err.message : "Unknown error";
        setError(message);
        setHealth(null);
        return false;
      }
    }
    async function fetchReady() {
      try {
        const url = `${apiBase}/health/ready`;
        setAttemptedReadyUrl(url);
        const res = await fetch(url);
        if (!res.ok) throw new Error(`Ready check failed: ${res.status}`);
        const payload = await res.text();
        setReady(payload);
        setReadyError(null);
        return true;
      } catch (err) {
        const message = err instanceof Error ? err.message : "Unknown error";
        setReadyError(message);
        setReady(null);
        return false;
      }
    }

    const run = async () => {
      setIsPolling(true);
      const [healthOk, readyOk] = await Promise.all([fetchHealth(), fetchReady()]);
      setLastUpdated(new Date().toLocaleTimeString());
      if (healthOk && readyOk) {
        setStarsActive(true);
        setTimeout(() => setStarsActive(false), 1400);
      }
      setTimeout(() => setIsPolling(false), 900);
    };

    run();
    const id = setInterval(run, 10_000);
    return () => clearInterval(id);
  }, [apiBase]);

  const badgeClass =
    health && health.status === "ok" && !error
      ? "status-pill ok"
      : "status-pill bad";

  const readyClass =
    ready && !readyError
      ? "status-pill ok"
      : "status-pill bad";

  return (
    <main className="page">
      <div className={`starfall ${starsActive ? "active" : ""}`} aria-hidden="true" />
      <div className="nebula" aria-hidden="true" />
      <header className="topbar">
        <div className="brand">
          <div className="logo-wrap">
            <Image
              src="/logo.png"
              alt="avaaz.ai logo"
              width={28}
              height={28}
              className="logo"
              priority
            />
          </div>
          avaaz.ai status
        </div>
        <div className={`pill subtle ${isPolling ? "pulse" : ""}`}>
          Polling every 10s
        </div>
      </header>

      <section className="hero">
        <div>
          <p className="eyebrow">System overview</p>
          <h1>Minimal health & readiness monitor</h1>
          <p className="lede">
            Inspired by gemini.google.com — lightweight cards, soft gradients,
            and live probes for backend health.
          </p>
          <div className="chip-row">
            <div className={badgeClass}>
              Health: {health && !error ? health.status : "unhealthy"}
            </div>
            <div className={readyClass}>
              Ready: {ready && !readyError ? ready : "not ready"}
            </div>
            {lastUpdated && (
              <div className="pill subtle">Updated {lastUpdated}</div>
            )}
          </div>
        </div>
      </section>

      <section className="grid">
        <article className="card glass">
          <div className="card-header">
            <span className="pill subtle">/health</span>
            <span className={badgeClass}>
              {health && !error ? health.status : "unhealthy"}
            </span>
          </div>
          <p className="muted">
            {attemptedHealthUrl || `${apiBase}/health`}
          </p>
          {health ? (
            <div className="meta">
              <div>
                <p className="meta-label">Status</p>
                <p className="meta-value">{health.status}</p>
              </div>
              {Object.entries(health.checks || {}).map(([key, val]) => (
                <div key={key}>
                  <p className="meta-label">{key}</p>
                  <p className="meta-value">{val.status}</p>
                </div>
              ))}
            </div>
          ) : (
            <p className="muted">{error || "Waiting for response..."}</p>
          )}
        </article>

        <article className="card glass">
          <div className="card-header">
            <span className="pill subtle">/health/ready</span>
            <span className={readyClass}>
              {ready && !readyError ? ready : "not ready"}
            </span>
          </div>
          <p className="muted">
            {attemptedReadyUrl || `${apiBase}/health/ready`}
          </p>
          {ready ? (
            <div className="meta">
              <div>
                <p className="meta-label">Status</p>
                <p className="meta-value">{ready}</p>
              </div>
            </div>
          ) : (
            <p className="muted">{readyError || "Waiting for response..."}</p>
          )}
        </article>
      </section>
    </main>
  );
}
