import * as React from "react";
import { type LucideIcon, BrainCircuit, Database, Layers } from "lucide-react";
import { cn } from "@/lib/utils";
import { formatCurrentMonthYear } from "@/lib/format-date";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import type {
  PolicyQueryContext,
  PolicyQueryType,
} from "./policy-ai-primitives";

// ---------------------------------------------------------------------------
// Props
// ---------------------------------------------------------------------------

export interface PolicyAIContextSidebarProps {
  /** Context detected from the most recent query (absent in home state). */
  lastQueryContext?: PolicyQueryContext;
  /** Follow-up question suggestions shown below the query context. */
  suggestedFollowUps?: string[];
  /** Called when user clicks a suggested follow-up question. */
  onFollowUpClick?: (question: string) => void;
  /** Number of banks indexed. Defaults to 0. */
  bankCount?: number;
  /** Number of policy categories indexed. Defaults to 0. */
  categoryCount?: number;
  /** Human-readable date of last policy update. Defaults to the current month. */
  lastUpdated?: string;
  className?: string;
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

const QUERY_TYPE_DESCRIPTIONS: Record<PolicyQueryType, string> = {
  single_bank: "Answered from a single bank's policy documents.",
  cross_bank_comparison: "Compared across all indexed banks simultaneously.",
  threshold_filter: "Filtered banks against a specific threshold or limit.",
  ranking: "Ranked banks using TOPSIS multi-criteria scoring.",
  scenario_match: "Matched your scenario against all bank lending criteria.",
  general: "General policy question answered from the knowledge base.",
};

const QUERY_TYPE_LABELS: Record<PolicyQueryType, string> = {
  single_bank: "Single bank",
  cross_bank_comparison: "Cross-bank",
  threshold_filter: "Threshold filter",
  ranking: "Ranked list",
  scenario_match: "Scenario match",
  general: "General",
};

// ---------------------------------------------------------------------------
// Sub-components
// ---------------------------------------------------------------------------

function SidebarSection({
  title,
  children,
  className,
}: {
  title: string;
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <div className={cn("flex flex-col gap-2", className)}>
      <p className="text-overline text-muted-foreground px-3">{title}</p>
      {children}
    </div>
  );
}

function StatRow({
  icon: Icon,
  children,
}: {
  icon: LucideIcon;
  children: React.ReactNode;
}) {
  return (
    <div className="flex items-center gap-2.5">
      <Icon
        className="size-3.5 text-muted-foreground shrink-0"
        aria-hidden="true"
      />
      {children}
    </div>
  );
}

// ---------------------------------------------------------------------------
// PolicyAIContextSidebar (Organism)
// ---------------------------------------------------------------------------

/**
 * Right sidebar for the Policy AI dedicated page.
 * Displays:
 * - Coverage stats (banks + categories indexed)
 * - Last query context as a source reference card
 * - Suggested follow-up questions
 *
 * @example
 * <PolicyAIContextSidebar
 *   lastQueryContext={lastMessage?.queryContext}
 *   suggestedFollowUps={["What about NAB?", "Show me ranked list"]}
 *   onFollowUpClick={handleSend}
 * />
 */
export function PolicyAIContextSidebar({
  lastQueryContext,
  suggestedFollowUps,
  onFollowUpClick,
  bankCount = 0,
  categoryCount = 0,
  lastUpdated = formatCurrentMonthYear(),
  className,
}: PolicyAIContextSidebarProps) {
  return (
    <div
      data-slot="policy-ai-context-sidebar"
      className={cn(
        "flex flex-col h-full border-l border-border bg-card shrink-0 overflow-y-auto",
        className,
      )}
    >
      <div className="flex flex-col gap-5 px-0 py-4">
        {/* ── Coverage stats ── */}
        <SidebarSection title="Coverage">
          <div className="flex flex-col gap-1.5 px-3">
            <StatRow icon={BrainCircuit}>
              <span className="text-sm text-foreground">
                <span className="font-semibold">{bankCount}</span> banks indexed
              </span>
            </StatRow>
            <StatRow icon={Layers}>
              <span className="text-sm text-foreground">
                <span className="font-semibold">{categoryCount}</span> policy
                categories
              </span>
            </StatRow>
            <StatRow icon={Database}>
              <span className="text-caption text-muted-foreground">
                Updated {lastUpdated}
              </span>
            </StatRow>
          </div>
        </SidebarSection>

        {/* ── Last query context — source reference card ── */}
        {lastQueryContext && (
          <>
            <Separator />
            <SidebarSection title="Last Query">
              {/*
               * Styled as a "source" card — three zones:
               *   Header  → policy type + query type badge
               *   Body    → bank name + category badges
               *   Footer  → one-line method description
               */}
              <Card className="gap-0 py-0 shadow-none overflow-hidden mx-3">
                {/* Header */}
                <div className="flex items-center justify-between gap-2 px-3 py-2 border-b border-border bg-muted/30">
                  <span className="text-sm font-semibold text-foreground">
                    {lastQueryContext.policyType}
                  </span>
                  <Badge variant="outline" className="text-xs shrink-0">
                    {QUERY_TYPE_LABELS[lastQueryContext.queryType]}
                  </Badge>
                </div>

                {/* Body */}
                <div className="flex flex-col gap-2 px-3 py-2.5">
                  {lastQueryContext.bankName && (
                    <p className="text-sm font-semibold text-foreground leading-none">
                      {lastQueryContext.bankName}
                    </p>
                  )}
                  {lastQueryContext.categories.length > 0 && (
                    <div className="flex flex-wrap gap-1">
                      {lastQueryContext.categories.map((cat) => (
                        <Badge
                          key={cat}
                          variant="secondary"
                          className="text-xs font-normal"
                        >
                          {cat}
                        </Badge>
                      ))}
                    </div>
                  )}
                </div>

                {/* Footer — method description */}
                <div className="border-t border-border px-3 py-2">
                  <p className="text-caption text-muted-foreground leading-snug">
                    {QUERY_TYPE_DESCRIPTIONS[lastQueryContext.queryType]}
                  </p>
                </div>
              </Card>
            </SidebarSection>
          </>
        )}

        {/* ── Suggested follow-ups ── */}
        {!!suggestedFollowUps?.length && (
          <>
            <Separator />
            <SidebarSection title="Follow-ups">
              <div className="flex flex-col gap-1 px-3">
                {suggestedFollowUps.map((q) => (
                  <Button
                    key={q}
                    variant="outline"
                    size="sm"
                    className="w-full justify-start h-auto py-1.5 text-muted-foreground font-normal leading-snug whitespace-normal text-left"
                    onClick={() => onFollowUpClick?.(q)}
                  >
                    {q}
                  </Button>
                ))}
              </div>
            </SidebarSection>
          </>
        )}
      </div>
    </div>
  );
}
