import { Paperclip } from "lucide-react";
import { cn } from "@/lib/utils";
import type { QueryMessage } from "@/lib/ledger-types";

export function QueryThread({ messages }: { messages?: QueryMessage[] | null }) {
  const rows = Array.isArray(messages) ? messages.filter(Boolean) : [];
  if (!rows.length) {
    return <p className="text-[13px] text-muted-foreground">No messages yet.</p>;
  }

  return (
    <div className="space-y-3">
      {rows.map((msg) => (
        <article
          key={msg.id}
          className={cn(
            "rounded-lg border p-4",
            msg.senderRole === "firm"
              ? "border-border bg-muted/30"
              : "border-primary/15 bg-primary-soft/40",
          )}
        >
          <div className="flex flex-wrap items-center justify-between gap-2">
            <p className="text-[12px] font-semibold text-foreground">
              {msg.senderRole === "firm" ? "Accountant" : "Client"}
              {msg.senderName ? ` · ${msg.senderName}` : ""}
            </p>
            <time className="text-[11px] text-muted-foreground">{msg.createdAt}</time>
          </div>
          <p className="mt-2 text-[13.5px] leading-6 text-foreground">{msg.message}</p>
          {msg.attachmentRef ? (
            <p className="mt-2 flex items-center gap-1.5 text-[12px] text-primary">
              <Paperclip size={12} aria-hidden="true" />
              {msg.attachmentRef}
            </p>
          ) : null}
        </article>
      ))}
    </div>
  );
}

export function QueryPriorityBadge({ priority }: { priority?: string }) {
  const value = priority || "Normal";
  const tone =
    value === "High"
      ? "border-attention/25 bg-attention-soft text-attention"
      : value === "Low"
        ? "border-border bg-muted text-muted-foreground"
        : "border-primary/20 bg-primary-soft text-primary";
  return (
    <span className={cn("inline-flex rounded-full border px-2.5 py-1 text-[11px] font-medium", tone)}>
      {value}
    </span>
  );
}

export function queryStatusTone(status?: string): "neutral" | "green" | "amber" | "danger" {
  switch (status) {
    case "Resolved":
      return "green";
    case "Answered":
      return "amber";
    case "Delivered":
      return "amber";
    case "Cancelled":
      return "neutral";
    default:
      return "neutral";
  }
}
