"use client";

import { useState, useCallback } from "react";
import { useRouter } from "next/navigation";
import { StemeDBClient, type SkepticResponse, ApiError } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { QueryForm, type QueryParams } from "./query-form";
import { EmptyState } from "./empty-state";
import { LoadingSkeleton } from "./loading-skeleton";
import { ErrorState } from "./error-state";
import { StatusBadge } from "./status-badge";
import { ConflictGauge } from "./conflict-gauge";
import { ClaimsTable } from "./claims-table";
import { WeightDistribution } from "./weight-distribution";
import type { ConflictStatus } from "./constants";

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

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

  const handleViewAudit = useCallback(
    (subject: string, predicate: string) => {
      // Navigate to audit page with query params for filtering
      const params = new URLSearchParams({ subject, predicate });
      router.push(`/audit?${params.toString()}`);
    },
    [router]
  );

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

    try {
      const client = new StemeDBClient();
      const data = await client.skeptic(
        params.subject,
        params.predicate,
        params.includeSourceMetadata,
        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">
          Conflict Analysis 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" && <LoadingSkeleton />}

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

        {state.status === "success" && (
          <div className="space-y-6">
            {/* Header with query info and status */}
            <div className="flex items-center justify-between flex-wrap gap-4">
              <div>
                <h3 className="text-lg font-medium text-foreground">
                  Results for{" "}
                  <code className="bg-muted px-1.5 py-0.5 rounded text-sm">
                    {state.data.subject}
                  </code>
                  {" → "}
                  <code className="bg-muted px-1.5 py-0.5 rounded text-sm">
                    {state.data.predicate}
                  </code>
                </h3>
                <p className="text-xs text-muted-foreground mt-1">
                  Resolved via {state.data.lens_name} •{" "}
                  {new Date(state.data.computed_at).toLocaleString()}
                </p>
              </div>
              <div className="flex items-center gap-3">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() =>
                    handleViewAudit(state.data.subject, state.data.predicate)
                  }
                >
                  View Audit Trail
                </Button>
                <StatusBadge status={state.data.status as ConflictStatus} />
              </div>
            </div>

            {/* Conflict Gauge */}
            <ConflictGauge
              score={state.data.conflict_score}
              status={state.data.status as ConflictStatus}
            />

            {/* Weight Distribution Chart */}
            {state.data.claims.length > 1 && (
              <WeightDistribution claims={state.data.claims} maxDisplay={5} />
            )}

            {/* Stats Row */}
            <div className="flex gap-6 text-sm border-t border-border pt-4">
              <div>
                <span className="text-muted-foreground">Total Assertions: </span>
                <span className="font-semibold">{state.data.candidates_count}</span>
              </div>
              <div>
                <span className="text-muted-foreground">Distinct Claims: </span>
                <span className="font-semibold">{state.data.claims.length}</span>
              </div>
              <div>
                <span className="text-muted-foreground">Status: </span>
                <span className="font-semibold">{state.data.status}</span>
              </div>
            </div>

            {/* Claims Table */}
            <div className="border-t border-border pt-4">
              <ClaimsTable claims={state.data.claims} />
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
