"use client";

import { useState, useMemo, useCallback } from "react";
import { useRouter } from "next/navigation";
import type { LayeredResponse } from "@/lib/api/types";
import { Button } from "@/components/ui/button";
import { CrossTierConflictSummary } from "./cross-tier-summary";
import { TierAccordion } from "./tier-accordion";

interface LayeredResultsViewProps {
  data: LayeredResponse;
}

export function LayeredResultsView({ data }: LayeredResultsViewProps) {
  const router = useRouter();

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

  // Filter to only tiers that have winners, sorted by tier number (T0 first)
  const tiersWithWinners = useMemo(
    () =>
      (data.tiers || [])
        .filter((t) => t.winner)
        .sort((a, b) => a.tier - b.tier),
    [data.tiers]
  );

  // Track which tiers are expanded - default to first tier
  const [expandedTiers, setExpandedTiers] = useState<Set<number>>(() => {
    const initial = new Set<number>();
    if (tiersWithWinners.length > 0) {
      initial.add(tiersWithWinners[0].tier);
    }
    return initial;
  });

  const toggleTier = (tierNum: number) => {
    setExpandedTiers((prev) => {
      const next = new Set(prev);
      if (next.has(tierNum)) {
        next.delete(tierNum);
      } else {
        next.add(tierNum);
      }
      return next;
    });
  };

  if (tiersWithWinners.length === 0) {
    return (
      <div className="text-center py-8 text-muted-foreground">
        No claims found for this query.
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header with query info */}
      <div className="flex items-start justify-between">
        <div>
          <h3 className="text-lg font-medium text-foreground">
            Results for{" "}
            <code className="bg-muted px-1.5 py-0.5 rounded text-sm">
              {data.subject}
            </code>
            {" → "}
            <code className="bg-muted px-1.5 py-0.5 rounded text-sm">
              {data.predicate}
            </code>
          </h3>
          <p className="text-xs text-muted-foreground mt-1">
            Resolved via {data.lens_name}
          </p>
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={() => handleViewAudit(data.subject, data.predicate)}
        >
          View Audit Trail
        </Button>
      </div>

      {/* Cross-tier conflict summary */}
      <CrossTierConflictSummary
        crossTierConflict={data.overall_conflict_score}
        activeTiers={tiersWithWinners.length}
        totalCandidates={data.total_candidates}
      />

      {/* Overall winner highlight */}
      {data.overall_winner && (
        <div className="rounded-lg border-2 border-primary/50 bg-primary/5 p-4">
          <div className="flex items-center gap-2 mb-2">
            <span className="text-xs font-medium text-primary uppercase tracking-wide">
              Overall Winner
            </span>
            <span className="text-xs text-muted-foreground">
              T{tiersWithWinners.find(t => t.winner?.hash === data.overall_winner?.hash)?.tier ?? 0} {data.overall_winner.source_class}
            </span>
          </div>
          <p className="text-foreground font-medium">
            {String(data.overall_winner.object.value)}
          </p>
          <p className="text-xs text-muted-foreground mt-1">
            Confidence: {(data.overall_winner.confidence * 100).toFixed(0)}%
          </p>
        </div>
      )}

      {/* Tier accordions */}
      <div className="space-y-3">
        {tiersWithWinners.map((tier) => (
          <TierAccordion
            key={tier.tier}
            tier={tier}
            isExpanded={expandedTiers.has(tier.tier)}
            onToggle={() => toggleTier(tier.tier)}
          />
        ))}
      </div>

      {/* Metadata footer */}
      <div className="flex gap-6 text-sm border-t border-border pt-4 text-muted-foreground">
        <div>
          <span>Total Candidates: </span>
          <span className="font-semibold text-foreground">{data.total_candidates}</span>
        </div>
        <div>
          <span>Computed: </span>
          <span className="font-semibold text-foreground">
            {new Date(data.computed_at * 1000).toLocaleString()}
          </span>
        </div>
      </div>
    </div>
  );
}
