import * as React from "react";
import { Bot, CheckCircle2, AlertTriangle, XCircle } from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { Badge } from "@/components/ui/badge";

/**
 * AgentEvaluationToast — WealthX DS (L3 Molecule)
 *
 * Displays an agent's self-evaluation result after a task is assigned in the
 * AI pipeline stage flow. The agent reasons against the task description +
 * expectation and returns a confidence percentage plus a result:
 * - **Accepted** (≥70%) — agent has all inputs and will proceed autonomously
 * - **Partial** (40–69%) — agent will attempt but flagged uncertainty; may need
 *   broker review when done
 * - **Declined** (<40%) — agent lacks required context; task stays with broker
 *
 * ### Usage — as a Sonner toast
 * ```tsx
 * import { showAgentEvaluationToast } from "@wealthx/shadcn/agent-evaluation-toast";
 *
 * showAgentEvaluationToast({
 *   agentName: "Ledger Agent",
 *   taskName: "Run serviceability check",
 *   confidence: 84,
 *   result: "accepted",
 *   reasoning: "I have all required inputs to complete this task.",
 * });
 * ```
 *
 * ### Usage — as a standalone card (stories / inline display)
 * ```tsx
 * import { AgentEvaluationCard } from "@wealthx/shadcn/agent-evaluation-toast";
 *
 * <AgentEvaluationCard
 *   agentName="Ledger Agent"
 *   taskName="Run serviceability check"
 *   confidence={84}
 *   result="accepted"
 *   reasoning="I have all required inputs to complete this task."
 * />
 * ```
 */

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export type AgentEvaluationResult = "accepted" | "partial" | "declined";

export interface AgentEvaluationData {
  agentName: string;
  taskName: string;
  /** Agent confidence — 0 to 100. */
  confidence: number;
  result: AgentEvaluationResult;
  /** Brief agent reasoning shown below the headline. */
  reasoning: string;
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

const RESULT_CONFIG: Record<
  AgentEvaluationResult,
  {
    label: string;
    icon: React.ElementType;
    badgeClass: string;
    borderClass: string;
  }
> = {
  accepted: {
    label: "Accepted",
    icon: CheckCircle2,
    badgeClass: "border-success/40 bg-success/10 text-success-text gap-1",
    borderClass: "border-success/30",
  },
  partial: {
    label: "Partial match",
    icon: AlertTriangle,
    badgeClass: "border-warning/40 bg-warning/10 text-warning-text gap-1",
    borderClass: "border-warning/30",
  },
  declined: {
    label: "Declined",
    icon: XCircle,
    badgeClass:
      "border-destructive/40 bg-destructive/10 text-destructive-text gap-1",
    borderClass: "border-destructive/30",
  },
};

// ---------------------------------------------------------------------------
// AgentEvaluationCard (standalone / inline)
// ---------------------------------------------------------------------------

export interface AgentEvaluationCardProps extends AgentEvaluationData {
  className?: string;
}

export function AgentEvaluationCard({
  agentName,
  taskName,
  confidence,
  result,
  reasoning,
  className,
}: AgentEvaluationCardProps) {
  const cfg = RESULT_CONFIG[result];
  const Icon = cfg.icon;

  return (
    <div
      className={cn(
        "flex flex-col gap-2 rounded border bg-card p-3 text-sm shadow-sm",
        cfg.borderClass,
        className,
      )}
    >
      {/* Header row */}
      <div className="flex items-start justify-between gap-3">
        <div className="flex items-center gap-2 min-w-0">
          <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded border bg-muted">
            <Bot className="size-3.5 text-muted-foreground" />
          </span>
          <div className="min-w-0">
            <p className="truncate font-medium text-foreground leading-tight">
              {agentName}
            </p>
            <p className="truncate text-xs text-muted-foreground">
              evaluated &ldquo;{taskName}&rdquo;
            </p>
          </div>
        </div>
        <Badge
          variant="outline"
          className={cn("shrink-0 text-[11px]", cfg.badgeClass)}
        >
          <Icon className="size-3" />
          {cfg.label}
        </Badge>
      </div>

      {/* Confidence bar */}
      <div className="flex items-center gap-2">
        <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-muted">
          <div
            className={cn(
              "h-full rounded-full transition-all",
              result === "accepted"
                ? "bg-success"
                : result === "partial"
                  ? "bg-warning"
                  : "bg-destructive",
            )}
            style={{ width: `${confidence}%` }}
          />
        </div>
        <span className="shrink-0 text-xs font-medium text-foreground tabular-nums">
          {confidence}%
        </span>
      </div>

      {/* Reasoning */}
      <p className="text-xs text-muted-foreground leading-relaxed">
        &ldquo;{reasoning}&rdquo;
      </p>
    </div>
  );
}

// ---------------------------------------------------------------------------
// showAgentEvaluationToast (Sonner integration)
// ---------------------------------------------------------------------------

/**
 * Fire a Sonner toast showing the agent's evaluation result.
 * Requires `<Toaster />` to be mounted in the app.
 */
export function showAgentEvaluationToast(data: AgentEvaluationData): void {
  toast.custom(
    () => (
      <div className="w-[360px]">
        <AgentEvaluationCard {...data} />
      </div>
    ),
    { duration: 6000 },
  );
}
