"use client";

import { Suspense, useMemo } from "react";
import { useSearchParams } from "next/navigation";
import { ButtonLink } from "@/components/ui/Button";
import { useObserveData } from "./hooks/use-observe-data";
import { SummarySection } from "./sections/summary-section";
import {
  TREND_TOOLTIP_LIST_CLASS,
  TREND_TOOLTIP_WRAPPER_STYLE,
  TrendsSection,
} from "./sections/trends-section";
import { LogsSection } from "./sections/logs-section";
import { QueryErrorBanner } from "./components/query-error-banner";
import { ObserveViewSwitcher } from "./components/observe-view-switcher";
import { SectionLoadingCard } from "./components/section-loading-card";
import {
  buildTrendTooltipRows,
  buildTrendXAxisTicks,
  formatTrendRegionLabel,
  resolveAgentResourcesTooltipPlacement,
  tooltipSortKey,
} from "./lib/chart";

export {
  buildTrendTooltipRows,
  buildTrendXAxisTicks,
  formatTrendRegionLabel,
  resolveAgentResourcesTooltipPlacement,
  tooltipSortKey,
  TREND_TOOLTIP_LIST_CLASS,
  TREND_TOOLTIP_WRAPPER_STYLE,
};

function ObservePageContent() {
  const searchParams = useSearchParams();
  const regionIds = useMemo(() => {
    const raw = searchParams.get("regions") || "";
    return raw
      .split(",")
      .map((regionId) => regionId.trim())
      .filter(Boolean);
  }, [searchParams]);

  const {
    summary,
    trends,
    logs,
    loading,
    trendsLoading,
    logsLoading,
    summaryError,
    trendsError,
    logsError,
    rangeMinutes,
    setRangeMinutes,
    logsRangeMinutes,
    setLogsRangeMinutes,
    logsFilterMode,
    logsFilterKeyword,
    loadSummary,
    loadTrends,
    applyLogsFilterAndLoad,
  } = useObserveData(regionIds);

  if (regionIds.length === 0) {
    return (
      <div className="space-y-6 animate-fade-in">
        <section>
          <h2 className="text-xl font-semibold tracking-tight">Observe</h2>
        </section>
        <section className="bg-surface-0 border border-surface-2 rounded-lg p-6 max-w-lg">
          <h3 className="text-lg font-semibold">Select regions first</h3>
          <p className="mt-2 text-sm text-text-secondary">
            Choose regions on the Regions page, then return to this workflow.
          </p>
          <ButtonLink
            href="/regions"
            size="sm"
            className="mt-4"
          >
            Go to Regions
          </ButtonLink>
        </section>
      </div>
    );
  }

  return (
    <div className="space-y-6 animate-fade-in">
      <section className="flex items-start justify-between gap-4">
        <div>
          <h2 className="text-xl font-semibold tracking-tight">Observe</h2>
        </div>
        <ObserveViewSwitcher activeView="observe" regionIds={regionIds} />
      </section>

      <QueryErrorBanner title="Failed to load Summary" message={summaryError} />

      {summary && (
        <SummarySection summary={summary} loading={loading} onRefresh={loadSummary} />
      )}
      {!summary && loading ? (
        <SectionLoadingCard
          label="Loading Summary"
          testId="summary-loading"
        />
      ) : null}
      <TrendsSection
        trends={trends}
        trendsLoading={trendsLoading}
        trendsError={trendsError}
        rangeMinutes={rangeMinutes}
        setRangeMinutes={setRangeMinutes}
        onRefresh={loadTrends}
        xAxisTicksBuilder={buildTrendXAxisTicks}
      />
      <LogsSection
        logs={logs}
        logsLoading={logsLoading}
        logsError={logsError}
        logsFilterMode={logsFilterMode}
        logsFilterKeyword={logsFilterKeyword}
        logsRangeMinutes={logsRangeMinutes}
        setLogsRangeMinutes={setLogsRangeMinutes}
        onRefresh={applyLogsFilterAndLoad}
      />
    </div>
  );
}

function ObservePageSkeleton() {
  return (
    <div className="space-y-6 animate-fade-in">
      <section>
        <h2 className="text-xl font-semibold tracking-tight">Observe</h2>
      </section>
      <section className="bg-surface-0 border border-surface-2 rounded-lg p-6 max-w-2xl">
        <div className="h-5 w-32 rounded bg-surface-2" />
        <div className="mt-3 h-4 w-72 max-w-full rounded bg-surface-2/70" />
      </section>
    </div>
  );
}

export default function ObservePage() {
  return (
    <Suspense fallback={<ObservePageSkeleton />}>
      <ObservePageContent />
    </Suspense>
  );
}
