import * as React from "react";
import {
  Check,
  ChevronDown,
  ChevronUp,
  ExternalLink,
  MapPin,
  MousePointerClick,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";

/**
 * Support Agent Primitives — WealthX DS
 *
 * Atomic building blocks for the Support Agent panel.
 * Inspired by Jira Rovo's sidebar chat pattern:
 *   - SupportContextChip   — shows current backoffice page + entity (Rovo: page context header)
 *   - SupportSuggestedQuestion — clickable question cards (Rovo: conversation starters)
 *   - SupportStepGuideCard — numbered walkthrough with "Show me" DOM highlight (Rovo: message cards)
 *   - SupportArticleCard   — help article reference link (Rovo: linked content cards)
 *
 * All components are pure display — no state or API calls.
 * State and event handling are managed by SupportAgentPanel (the parent organism).
 */

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

/** Context injected from the current backoffice route. */
export interface SupportAgentContext {
  /** Page label from the current route, e.g. "Loan Applications". */
  pageLabel: string;
  /** Entity currently being viewed, e.g. "John Smith". Optional. */
  entityLabel?: string;
  /** Entity type for semantic use, e.g. "client" | "application" | "contact". */
  entityType?: string;
}

/** A single step inside a SupportStepGuideCard. */
export interface SupportAgentStep {
  id: string;
  /** Human-readable step instruction. */
  label: string;
  /**
   * If set, the "Show me" button fires onHighlight(elementId).
   * The consuming page listens for this and highlights the DOM element
   * that has data-support-id matching this value.
   */
  elementId?: string;
  /** Whether the user has marked this step as done. */
  completed?: boolean;
}

/** Rich content embedded inside an assistant message bubble. */
export type SupportAgentRichContent =
  | {
      type: "step-guide";
      title: string;
      steps: SupportAgentStep[];
    }
  | {
      type: "article";
      title: string;
      excerpt: string;
      href: string;
      /** If true, opens in a new tab and shows an external link icon. */
      isExternal?: boolean;
    };

// ---------------------------------------------------------------------------
// SupportContextChip
// ---------------------------------------------------------------------------

export interface SupportContextChipProps {
  context?: SupportAgentContext;
  /** Show a skeleton loading placeholder. */
  isLoading?: boolean;
  className?: string;
}

/**
 * Pill that shows the current backoffice page and optional entity.
 * Appears below the panel header to ground the AI conversation in context.
 *
 * Variants:
 *   - page-only   → "📍 Loan Applications"
 *   - page+entity → "📍 Loan Applications  ›  John Smith"
 *   - loading     → skeleton placeholder
 */
export function SupportContextChip({
  context,
  isLoading = false,
  className,
}: SupportContextChipProps) {
  if (isLoading) {
    return (
      <Skeleton
        className={cn("h-6 w-48", className)}
        data-slot="support-context-chip"
      />
    );
  }

  if (!context) return null;

  return (
    <div
      className={cn(
        "flex w-fit items-center gap-1.5 bg-muted px-2.5 py-1 text-xs text-muted-foreground",
        className
      )}
      data-slot="support-context-chip"
    >
      <MapPin className="size-3 shrink-0" aria-hidden="true" />
      <span className="font-medium text-foreground">{context.pageLabel}</span>
      {context.entityLabel && (
        <>
          <span aria-hidden="true">›</span>
          <span className="truncate max-w-[160px]">{context.entityLabel}</span>
        </>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// SupportSuggestedQuestion
// ---------------------------------------------------------------------------

export interface SupportSuggestedQuestionProps {
  question: string;
  onSelect: (question: string) => void;
  className?: string;
}

/**
 * Single clickable question card — the Jira Rovo "conversation starter" pattern.
 * Clicking pre-fills the chat input with the question text.
 */
export function SupportSuggestedQuestion({
  question,
  onSelect,
  className,
}: SupportSuggestedQuestionProps) {
  return (
    <Button
      type="button"
      variant="ghost"
      onClick={() => onSelect(question)}
      className={cn(
        "h-auto w-full justify-start border border-border bg-background px-3 py-2.5 text-left text-sm font-normal text-foreground hover:bg-muted/50",
        className
      )}
      data-slot="support-suggested-question"
    >
      {question}
    </Button>
  );
}

// ---------------------------------------------------------------------------
// SupportStepGuideCard
// ---------------------------------------------------------------------------

export interface SupportStepGuideCardProps {
  title: string;
  steps: SupportAgentStep[];
  /** Called when the user clicks "Show me" on a step that has an elementId. */
  onHighlight?: (elementId: string) => void;
  /** Called when the user marks a step as complete. */
  onStepComplete?: (stepId: string) => void;
  /** Default collapsed if more than 5 steps; otherwise expanded. */
  defaultExpanded?: boolean;
  className?: string;
}

/**
 * A numbered walkthrough card embedded inside an AI assistant message bubble.
 * Inspired by Jira Rovo message cards — bordered container with structured content.
 *
 * - Completed steps show a checkmark icon instead of a number.
 * - Steps with an `elementId` show a "→ Show me" button that fires onHighlight.
 * - Collapsible when more than 5 steps (default collapsed).
 */
export function SupportStepGuideCard({
  title,
  steps,
  onHighlight,
  onStepComplete,
  defaultExpanded,
  className,
}: SupportStepGuideCardProps) {
  const isLong = steps.length > 5;
  const [expanded, setExpanded] = React.useState(defaultExpanded ?? !isLong);

  const completedCount = steps.filter((s) => s.completed).length;
  const allDone = completedCount === steps.length;

  return (
    <div
      className={cn("mt-2 border border-border bg-background", className)}
      data-slot="support-step-guide-card"
    >
      {/* Card header */}
      <button
        type="button"
        onClick={() => setExpanded((v) => !v)}
        className="flex w-full items-center justify-between gap-2 px-3 py-2.5 text-left hover:bg-muted/30"
        aria-expanded={expanded}
      >
        <div className="flex flex-col gap-0.5">
          <span className="text-sm font-semibold text-foreground">{title}</span>
          <span className="text-xs text-muted-foreground">
            {allDone
              ? "All steps complete"
              : `${completedCount} of ${steps.length} complete`}
          </span>
        </div>
        {expanded ? (
          <ChevronUp
            className="size-4 shrink-0 text-muted-foreground"
            aria-hidden="true"
          />
        ) : (
          <ChevronDown
            className="size-4 shrink-0 text-muted-foreground"
            aria-hidden="true"
          />
        )}
      </button>

      {/* Steps list */}
      {expanded && (
        <ol className="flex flex-col divide-y divide-border border-t border-border">
          {steps.map((step, index) => (
            <li
              key={step.id}
              className={cn(
                "flex items-start gap-3 px-3 py-2.5",
                step.completed && "opacity-60"
              )}
            >
              {/* Step number or checkmark */}
              <button
                type="button"
                onClick={() => !step.completed && onStepComplete?.(step.id)}
                disabled={step.completed}
                title={step.completed ? "Step complete" : "Mark as done"}
                className={cn(
                  "mt-0.5 flex size-5 shrink-0 items-center justify-center border text-xs font-semibold",
                  step.completed
                    ? "border-primary bg-primary text-primary-foreground"
                    : "border-border text-muted-foreground hover:bg-muted"
                )}
                aria-label={
                  step.completed
                    ? `Step ${index + 1} complete`
                    : `Mark step ${index + 1} as done`
                }
              >
                {step.completed ? (
                  <Check className="size-3" aria-hidden="true" />
                ) : (
                  index + 1
                )}
              </button>

              {/* Step label + show me button */}
              <div className="flex flex-1 flex-col gap-1">
                <span className="text-sm text-foreground leading-snug">
                  {step.label}
                </span>
                {step.elementId && onHighlight && !step.completed && (
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => onHighlight(step.elementId!)}
                    className="h-auto w-fit gap-1 px-0 py-0 text-xs text-primary hover:bg-transparent hover:underline"
                  >
                    <MousePointerClick className="size-3" aria-hidden="true" />
                    Show me
                  </Button>
                )}
              </div>
            </li>
          ))}
        </ol>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// SupportArticleCard
// ---------------------------------------------------------------------------

export interface SupportArticleCardProps {
  title: string;
  excerpt: string;
  href: string;
  /** If true, opens in a new tab with an external link icon. */
  isExternal?: boolean;
  className?: string;
}

/**
 * A compact help article reference card embedded inside an AI message bubble.
 * Inspired by Jira Rovo's linked content cards.
 *
 * - Internal links: navigates in the same tab (relative URL).
 * - External links: opens new tab + shows ExternalLink icon.
 */
export function SupportArticleCard({
  title,
  excerpt,
  href,
  isExternal = false,
  className,
}: SupportArticleCardProps) {
  return (
    <a
      href={href}
      target={isExternal ? "_blank" : undefined}
      rel={isExternal ? "noopener noreferrer" : undefined}
      className={cn(
        "mt-2 flex flex-col gap-1.5 border border-border bg-background px-3 py-2.5 text-left no-underline hover:bg-muted/30 text-foreground",
        className
      )}
      data-slot="support-article-card"
    >
      <div className="flex items-center justify-between gap-2">
        <span className="min-w-0 flex-1 truncate text-sm font-semibold text-foreground">
          {title}
        </span>
        {isExternal && (
          <ExternalLink
            className="size-3.5 shrink-0 text-muted-foreground"
            aria-hidden="true"
          />
        )}
      </div>
      <p className="text-xs text-muted-foreground line-clamp-2 leading-relaxed">
        {excerpt}
      </p>
      <span className="text-xs font-medium text-primary">
        {isExternal ? "Open article →" : "Read more →"}
      </span>
    </a>
  );
}
