import React, { useEffect, useState } from "react";
import type { CheckResult, ClientSite } from "../types";
import { api } from "../api";
export function HistoryPanel({ site }: { site: ClientSite }) {
  const [checks, setChecks] = useState<CheckResult[]>([]);
  const [error, setError] = useState("");
  useEffect(() => {
    let alive = true;
    api<CheckResult[]>(`/api/sites/${site.id}/history`)
      .then((rows) => {
        if (alive) {
          setChecks(rows);
          setError("");
        }
      })
      .catch((e) => {
        if (alive) setError(e.message);
      });
    return () => {
      alive = false;
    };
  }, [site.id, site.lastResult?.checkedAt]);
  const samples = checks.slice(-60);
  const max = Math.max(100, ...samples.map((c) => c.responseTimeMs));
  const points = samples
    .map(
      (c, i) =>
        `${20 + (i * 560) / Math.max(1, samples.length - 1)},${125 - (c.responseTimeMs / max) * 100}`,
    )
    .join(" ");
  const known = checks.filter((c) => c.status !== "unknown");
  const successful = known.filter(
    (c) => c.status === "online" || c.status === "warning",
  );
  return (
    <div className="bg-slate-900 border border-slate-700 rounded-xl p-5 space-y-3">
      <h3 className="font-semibold">Sejarah semakan — {site.name}</h3>
      {error ? (
        <p className="text-red-300 text-sm">{error}</p>
      ) : !checks.length ? (
        <p className="text-sm text-slate-400">Belum ada rekod semakan.</p>
      ) : (
        <>
          <p className="text-sm text-slate-400">
            {known.length
              ? `${Math.round((successful.length / known.length) * 100)}% semakan berjaya daripada ${known.length} semakan yang diketahui.`
              : "Tiada keputusan yang boleh disahkan."}{" "}
            Ini kadar semakan, bukan ukuran tempoh uptime.
          </p>
          <svg
            viewBox="0 0 600 160"
            role="img"
            aria-label="Graf masa respons bagi 60 semakan terkini"
            className="w-full max-h-48"
          >
            <line x1="20" x2="580" y1="125" y2="125" stroke="#475569" />
            <polyline
              points={points}
              fill="none"
              stroke="#60a5fa"
              strokeWidth="2"
            />
            {samples.map((c, i) => (
              <circle
                key={i}
                cx={20 + (i * 560) / Math.max(1, samples.length - 1)}
                cy={125 - (c.responseTimeMs / max) * 100}
                r="3"
                fill={
                  c.status === "down" || c.status === "error"
                    ? "#f87171"
                    : c.status === "unknown"
                      ? "#94a3b8"
                      : "#34d399"
                }
              />
            ))}
            <text x="20" y="150" fill="#94a3b8" fontSize="11">
              {samples[0] &&
                new Date(samples[0].checkedAt).toLocaleString("ms-MY", {
                  timeZone: "Asia/Kuala_Lumpur",
                })}
            </text>
            <text x="580" y="150" textAnchor="end" fill="#94a3b8" fontSize="11">
              Maksimum {max} ms
            </text>
          </svg>
          <div className="max-h-40 overflow-auto text-xs">
            {checks
              .slice(-10)
              .reverse()
              .map((c, i) => (
                <div
                  key={i}
                  className="flex flex-wrap justify-between gap-2 border-t border-slate-800 py-2"
                >
                  <span>
                    {new Date(c.checkedAt).toLocaleString("ms-MY", {
                      timeZone: "Asia/Kuala_Lumpur",
                    })}
                  </span>
                  <span>
                    {c.status} · HTTP {c.statusCode || "—"} · {c.responseTimeMs}{" "}
                    ms
                  </span>
                </div>
              ))}
          </div>
        </>
      )}
    </div>
  );
}
