"use client";

import { useState, useCallback } from "react";
import { StemeDBClient, type LayeredResponse, ApiError } from "@/lib/api";
import { QueryForm, type QueryParams, EmptyState, ErrorState } from "@/components/skeptic";
import { LayeredLoadingSkeleton } from "./layered-loading-skeleton";
import { LayeredResultsView } from "./layered-results-view";

type QueryState =
  | { status: "idle" }
  | { status: "loading"; params: QueryParams }
  | { status: "success"; data: LayeredResponse; params: QueryParams }
  | { status: "error"; error: string; params: QueryParams };

export function LayeredQueryResults() {
  const [state, setState] = useState<QueryState>({ status: "idle" });

  const executeQuery = useCallback(async (params: QueryParams) => {
    setState({ status: "loading", params });

    try {
      const client = new StemeDBClient();
      const data = await client.layered(params.subject, params.predicate, params.asOf);
      setState({ status: "success", data, params });
    } catch (err) {
      const errorMessage =
        err instanceof ApiError
          ? err.userMessage
          : err instanceof Error
            ? err.message
            : "Unknown error occurred";
      setState({ status: "error", error: errorMessage, params });
    }
  }, []);

  const handleRetry = useCallback(() => {
    if (state.status === "error") {
      executeQuery(state.params);
    }
  }, [state, executeQuery]);

  const isLoading = state.status === "loading";

  return (
    <div className="space-y-6">
      {/* Query Form */}
      <div className="rounded-lg border border-border bg-card p-6">
        <h2 className="text-lg font-medium text-card-foreground mb-4">
          Layered Consensus Query
        </h2>
        <QueryForm onSubmit={executeQuery} isLoading={isLoading} />
      </div>

      {/* Results Section */}
      <div className="rounded-lg border border-border bg-card p-6">
        {state.status === "idle" && <EmptyState />}

        {state.status === "loading" && <LayeredLoadingSkeleton />}

        {state.status === "error" && (
          <ErrorState error={state.error} onRetry={handleRetry} />
        )}

        {state.status === "success" && <LayeredResultsView data={state.data} />}
      </div>
    </div>
  );
}
