import { useCallback, useState, type ClipboardEvent } from "react";
import { RefreshButton } from "@/components/ui/Button";
import { formatRatio, formatText, formatUptime, formatUtc8Time } from "../lib/formatters";
import { resolveAgentResourcesTooltipPlacement } from "../lib/chart";
import { RegionStatusDot } from "../components/region-status-dot";
import type { AcsObserveSummary } from "@/lib/observe/summary";

const EMPTY_VALUE_LABEL = "-";
const INLINE_LABEL_CLASS = "w-11 shrink-0 text-[11px] font-medium text-text-muted";

function metricClass(value: number | null): string {
  if (value === null) return "text-text-muted";
  if (value >= 0.9) return "text-danger";
  if (value >= 0.75) return "text-warning";
  return "text-success";
}

function agentCrAlertClass(value: number | null): string {
  if (value === null) return "text-text-muted";
  return value > 0 ? "text-danger" : "text-success";
}

function agentControllerRestartClass(value: number | null): string {
  if (value === null) return "text-text-muted";
  return value > 0 ? "text-danger" : "text-success";
}

function runningGitHashClass(gitHash: string | null, configuredTag: string): string {
  if (!gitHash) return "text-text-muted";
  return gitHash === configuredTag ? "text-success" : "text-danger";
}

function handleTagCopy(event: ClipboardEvent<HTMLSpanElement>, value: string | null) {
  event.preventDefault();
  event.clipboardData.setData("text/plain", value ?? EMPTY_VALUE_LABEL);
}

export function SummarySection({
  summary,
  loading,
  onRefresh,
}: {
  summary: AcsObserveSummary;
  loading: boolean;
  onRefresh: () => void;
}) {
  return (
    <section data-testid="summary-section" className="space-y-4">
      <div className="flex items-center justify-between gap-4">
        <p className="text-sm text-text-secondary" data-testid="coverage-summary">
          <span className="font-medium text-text-primary" data-testid="coverage-selected">
            {summary.coverage.selected}
          </span>{" "}
          selected ·{" "}
          <span className="font-medium text-success" data-testid="coverage-ready">
            {summary.coverage.ready}
          </span>{" "}
          ready ·{" "}
          <span
            className={`font-medium ${summary.coverage.missingDatasource > 0 ? "text-danger" : "text-success"}`}
            data-testid="coverage-missing"
          >
            {summary.coverage.missingDatasource}
          </span>{" "}
          datasource missing
          {(summary.coverage.queryError ?? 0) > 0 ? (
            <>
              {" · "}
              <span className="font-medium text-danger" data-testid="coverage-query-error">
                {summary.coverage.queryError}
              </span>{" "}
              query error
            </>
          ) : null}
        </p>
        <RefreshButton
          aria-label="Refresh Summary"
          onClick={onRefresh}
          disabled={loading}
          busy={loading}
        />
      </div>
      <section className="bg-surface-0 border border-surface-2 rounded-lg overflow-visible">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-surface-2">
              <th className="px-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                Region
              </th>
              <th className="px-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                Tag
              </th>
              <th className="px-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                Build Branch
              </th>
              <th className="px-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                Build Time
              </th>
              <th className="px-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                Uptime
              </th>
              <th className="px-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                Restarts
              </th>
              <th className="px-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                Agent status
              </th>
              <th className="px-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                CPU Req
              </th>
              <th className="px-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                CPU Limit
              </th>
              <th className="px-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                Mem Req
              </th>
              <th className="px-4 py-2.5 text-left text-xs font-semibold uppercase tracking-wider text-text-muted">
                Mem Limit
              </th>
            </tr>
          </thead>
          <tbody>
            {summary.regions.map((row) => (
              <tr
                key={row.region.id}
                className="border-b border-surface-2/50 last:border-0 hover:bg-surface-1 transition-colors"
              >
                <td className="px-4 py-2.5">
                  <div className="flex items-center gap-2 font-medium">
                    <span>{row.region.regionName}</span>
                    <RegionStatusDot
                      status={row.status}
                      errorMessage={row.errorMessage}
                      fallbackErrorMessage="VictoriaMetrics query failed"
                    />
                  </div>
                  <div className="text-xs text-text-muted">
                    {row.region.architecture}/{row.region.environment}/{row.region.provider}
                  </div>
                </td>
                <TagCell configTag={row.region.currentTag} runningTag={row.build.gitHash} />
                <td className="px-4 py-2.5 font-mono text-[13px] text-text-secondary">
                  {formatText(row.build.branch)}
                </td>
                <td className="px-4 py-2.5">
                  <time
                    dateTime={row.build.time || undefined}
                    title={row.build.time || undefined}
                    className="font-mono text-[13px] bg-surface-1 px-2 py-0.5 rounded border border-surface-2/70 text-accent whitespace-nowrap"
                  >
                    {formatUtc8Time(row.build.time)}
                  </time>
                </td>
                <td className="px-4 py-2.5 font-mono text-[13px] text-text-secondary">
                  {formatUptime(row.uptimeSeconds)}
                </td>
                <AgentControllerRestartsCell value={row.agentControllerRestarts} />
                <AgentCrStatusCell status={row.agentCrStatus} />
                <MetricCell value={row.metrics.cpuRequestUsage} />
                <MetricCell value={row.metrics.cpuLimitUsage} />
                <MetricCell value={row.metrics.memoryRequestUsage} />
                <MetricCell value={row.metrics.memoryLimitUsage} />
              </tr>
            ))}
          </tbody>
        </table>
      </section>
    </section>
  );
}

function TagCell({
  configTag,
  runningTag,
}: {
  configTag: string;
  runningTag: string | null;
}) {
  const handleConfigCopy = useCallback(
    (event: ClipboardEvent<HTMLSpanElement>) => handleTagCopy(event, configTag),
    [configTag]
  );
  const handleRunningCopy = useCallback(
    (event: ClipboardEvent<HTMLSpanElement>) => handleTagCopy(event, runningTag),
    [runningTag]
  );

  return (
    <td className="px-4 py-2.5 font-mono text-[13px]">
      <div className="grid gap-1 leading-tight">
        <div className="flex items-baseline gap-2">
          <span className={INLINE_LABEL_CLASS}>Config</span>
          <span
            className="inline-block max-w-[24ch] truncate align-bottom text-text-secondary"
            title={configTag}
            onCopy={handleConfigCopy}
          >
            {formatText(configTag)}
          </span>
        </div>
        <div className="flex items-baseline gap-2">
          <span className={INLINE_LABEL_CLASS}>Running</span>
          <span
            className={`inline-block max-w-[24ch] truncate align-bottom ${runningGitHashClass(runningTag, configTag)}`}
            title={runningTag ?? undefined}
            onCopy={handleRunningCopy}
          >
            {formatText(runningTag)}
          </span>
        </div>
      </div>
    </td>
  );
}

function MetricCell({ value }: { value: number | null }) {
  return (
    <td className={`px-4 py-2.5 font-mono text-[13px] ${metricClass(value)}`}>
      {formatRatio(value)}
    </td>
  );
}

function AgentControllerRestartsCell({
  value,
}: {
  value?: AcsObserveSummary["regions"][number]["agentControllerRestarts"];
}) {
  const restarts = value ?? null;

  return (
    <td className={`px-4 py-2.5 font-mono text-[13px] ${agentControllerRestartClass(restarts)}`}>
      {restarts === null ? EMPTY_VALUE_LABEL : restarts}
    </td>
  );
}

function AgentCrStatusCell({
  status,
}: {
  status?: AcsObserveSummary["regions"][number]["agentCrStatus"];
}) {
  const [hovered, setHovered] = useState(false);
  const [tooltipPlacement, setTooltipPlacement] = useState<"above" | "below">("above");
  const normal = status?.normal ?? null;
  const hibernated = status?.hibernated ?? null;
  const paused = status?.paused ?? null;
  const abnormal = status?.abnormal ?? null;
  const specialConfig = status?.specialConfig ?? null;

  return (
    <td className="px-4 py-2.5 font-mono text-[13px]">
      <div
        className="relative inline-flex items-center gap-1 leading-tight whitespace-nowrap"
        onMouseEnter={(event) => {
          const { top, bottom } = event.currentTarget.getBoundingClientRect();
          setTooltipPlacement(
            resolveAgentResourcesTooltipPlacement(top, bottom, window.innerHeight)
          );
          setHovered(true);
        }}
        onMouseLeave={() => setHovered(false)}
      >
        <span className="inline-flex min-w-[2.4rem] items-center justify-between rounded-md border border-surface-2/60 bg-surface-1 px-1 py-0.5">
          <span className="text-[10px] text-text-muted">N:</span>
          <span className="text-text-secondary">{normal === null ? EMPTY_VALUE_LABEL : normal}</span>
        </span>
        <span className="inline-flex min-w-[2.4rem] items-center justify-between rounded-md border border-warning/20 bg-warning-muted px-1 py-0.5">
          <span className="text-[10px] text-text-muted">H:</span>
          <span className={agentCrAlertClass(hibernated)}>
            {hibernated === null ? EMPTY_VALUE_LABEL : hibernated}
          </span>
        </span>
        <span className="inline-flex min-w-[2.4rem] items-center justify-between rounded-md border border-arch-dedicated/20 bg-arch-dedicated/10 px-1 py-0.5">
          <span className="text-[10px] text-text-muted">P:</span>
          <span className={agentCrAlertClass(paused)}>
            {paused === null ? EMPTY_VALUE_LABEL : paused}
          </span>
        </span>
        <span className="inline-flex min-w-[2.4rem] items-center justify-between rounded-md border border-danger/20 bg-danger-muted px-1 py-0.5">
          <span className="text-[10px] text-text-muted">A:</span>
          <span className={agentCrAlertClass(abnormal)}>
            {abnormal === null ? EMPTY_VALUE_LABEL : abnormal}
          </span>
        </span>
        <span className="inline-flex min-w-[2.4rem] items-center justify-between rounded-md border border-accent/20 bg-accent/10 px-1 py-0.5">
          <span className="text-[10px] text-text-muted">S:</span>
          <span className={agentCrAlertClass(specialConfig)}>
            {specialConfig === null ? EMPTY_VALUE_LABEL : specialConfig}
          </span>
        </span>
        {hovered ? (
          <span
            role="tooltip"
            className={`pointer-events-none absolute left-1/2 z-10 -translate-x-1/2 rounded-lg border border-surface-2 bg-surface-0/95 px-2.5 py-2 text-[11px] text-text-primary shadow-xl backdrop-blur-sm ${tooltipPlacement === "above" ? "bottom-full mb-2" : "top-full mt-2"}`}
          >
            <span className="grid gap-1 whitespace-nowrap">
              <span className="inline-flex items-center gap-1.5">
                <span className="h-1.5 w-1.5 rounded-full bg-text-secondary" />
                {`Normal: ${normal ?? EMPTY_VALUE_LABEL}`}
              </span>
              <span className="inline-flex items-center gap-1.5">
                <span className="h-1.5 w-1.5 rounded-full bg-warning" />
                {`Hibernated: ${hibernated ?? EMPTY_VALUE_LABEL}`}
              </span>
              <span className="inline-flex items-center gap-1.5">
                <span className="h-1.5 w-1.5 rounded-full bg-danger" />
                {`Paused: ${paused ?? EMPTY_VALUE_LABEL}`}
              </span>
              <span className="inline-flex items-center gap-1.5">
                <span className="h-1.5 w-1.5 rounded-full bg-danger" />
                {`Abnormal: ${abnormal ?? EMPTY_VALUE_LABEL}`}
              </span>
              <span className="inline-flex items-center gap-1.5">
                <span className="h-1.5 w-1.5 rounded-full bg-accent" />
                {`SpecialConfig: ${specialConfig ?? EMPTY_VALUE_LABEL}`}
              </span>
            </span>
          </span>
        ) : null}
      </div>
    </td>
  );
}
