"use client";

import { useState, useMemo, useRef, useEffect } from "react";
import {
  CalendarIcon,
  ClockIcon,
  TagIcon,
  ArrowLeftIcon,
  PaperAirplaneIcon,
  EnvelopeIcon,
  ChatBubbleLeftIcon,
  PaperClipIcon,
  UserIcon,
  ChatBubbleLeftRightIcon,
  CheckIcon,
} from "@heroicons/react/24/outline";
import { TicketIcon as TicketIconSolid } from "@heroicons/react/24/solid";
import { PageLayout } from "@/components/templates/PageLayout";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { Button, Spinner } from "@/components/atoms";
import { useSupportCase } from "@/features/support/hooks/useSupportCase";
import { useCaseMessages } from "@/features/support/hooks/useCaseMessages";
import { useAddCaseComment } from "@/features/support/hooks/useAddCaseComment";
import {
  getCaseStatusIcon,
  getCaseStatusClasses,
  getCasePriorityClasses,
} from "@/features/support/utils";
import { formatIsoDate, formatIsoRelative } from "@/shared/utils";
import type { CaseMessage, SupportCase } from "@customer-portal/domain/support";
import { CLOSED_STATUSES } from "@customer-portal/domain/support";

const SUPPORT_HREF = "/account/support";
const AUTHOR_COLOR_MUTED = "text-primary-foreground/70";

// ============================================================================
// Helper Functions
// ============================================================================

/**
 * Group messages by date for better readability in long conversations
 */
interface MessageGroup {
  date: string;
  dateLabel: string;
  messages: CaseMessage[];
}

function groupMessagesByDate(messages: CaseMessage[]): MessageGroup[] {
  const groups: Map<string, CaseMessage[]> = new Map();

  for (const message of messages) {
    const date = new Date(message.createdAt);
    const dateKey = date.toISOString().split("T")[0]; // YYYY-MM-DD

    if (!dateKey) continue;
    if (!groups.has(dateKey)) {
      groups.set(dateKey, []);
    }
    groups.get(dateKey)?.push(message);
  }

  // Convert to array and add labels
  const today = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);

  const todayKey = today.toISOString().split("T")[0];
  const yesterdayKey = yesterday.toISOString().split("T")[0];

  return [...groups.entries()].map(([dateKey, msgs]) => {
    let dateLabel: string;
    if (dateKey === todayKey) {
      dateLabel = "Today";
    } else if (dateKey === yesterdayKey) {
      dateLabel = "Yesterday";
    } else {
      // Format as "Mon, Dec 30"
      const date = new Date(dateKey + "T00:00:00");
      dateLabel = date.toLocaleDateString("en-US", {
        weekday: "short",
        month: "short",
        day: "numeric",
      });
    }

    return {
      date: dateKey,
      dateLabel,
      messages: msgs,
    };
  });
}

/**
 * Group consecutive messages from the same sender within 5 minutes
 * for a cleaner conversation display
 */
interface SenderMessageGroup {
  senderId: string;
  isCustomer: boolean;
  messages: CaseMessage[];
}

function groupConsecutiveMessages(messages: CaseMessage[]): SenderMessageGroup[] {
  if (messages.length === 0) return [];

  const groups: SenderMessageGroup[] = [];
  let currentGroup: SenderMessageGroup | null = null;

  for (const message of messages) {
    const senderId = message.author.email ?? message.author.name;
    const isCustomer = message.author.isCustomer;

    // Check if this message should be part of the current group
    if (currentGroup && currentGroup.senderId === senderId) {
      const lastMessage = currentGroup.messages.at(-1);
      if (lastMessage) {
        const timeDiff =
          new Date(message.createdAt).getTime() - new Date(lastMessage.createdAt).getTime();
        const fiveMinutes = 5 * 60 * 1000;

        // Group if same sender and within 5 minutes
        if (timeDiff < fiveMinutes) {
          currentGroup.messages.push(message);
          continue;
        }
      }
    }

    // Start a new group
    currentGroup = {
      senderId,
      isCustomer,
      messages: [message],
    };
    groups.push(currentGroup);
  }

  return groups;
}

const CASE_VIEW_PREFIX = "case-";
const CASE_VIEW_SUFFIX = "-last-viewed";
const MAX_STORED_CASE_VIEWS = 50;

/**
 * Get the last viewed timestamp for a case from localStorage
 */
function getLastViewedTimestamp(caseId: string): string | null {
  if (typeof window === "undefined") return null;
  return localStorage.getItem(`${CASE_VIEW_PREFIX}${caseId}${CASE_VIEW_SUFFIX}`);
}

/**
 * Set the last viewed timestamp for a case in localStorage
 * Also cleans up old entries to prevent localStorage bloat
 */
function setLastViewedTimestamp(caseId: string): void {
  if (typeof window === "undefined") return;

  const key = `${CASE_VIEW_PREFIX}${caseId}${CASE_VIEW_SUFFIX}`;
  localStorage.setItem(key, new Date().toISOString());

  // Cleanup old entries if we have too many
  cleanupOldCaseViewTimestamps();
}

/**
 * Remove old case view timestamps to prevent localStorage bloat
 */
function cleanupOldCaseViewTimestamps(): void {
  // Collect all localStorage keys first to avoid iteration issues during removal
  const allKeys: string[] = [];
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i);
    if (key) allKeys.push(key);
  }

  // Filter to only case view keys and collect timestamps
  const caseViewKeys: { key: string; timestamp: number }[] = [];
  for (const key of allKeys) {
    if (key.startsWith(CASE_VIEW_PREFIX) && key.endsWith(CASE_VIEW_SUFFIX)) {
      const value = localStorage.getItem(key);
      const timestamp = value ? new Date(value).getTime() : 0;
      caseViewKeys.push({ key, timestamp });
    }
  }

  // If we have more than MAX entries, remove the oldest ones
  if (caseViewKeys.length > MAX_STORED_CASE_VIEWS) {
    caseViewKeys.sort((a, b) => b.timestamp - a.timestamp); // newest first
    const keysToRemove = caseViewKeys.slice(MAX_STORED_CASE_VIEWS);
    for (const { key } of keysToRemove) {
      localStorage.removeItem(key);
    }
  }
}

interface SupportCaseDetailViewProps {
  caseId: string;
}

function useCaseDetailState(caseId: string) {
  const { data: supportCase, error, refetch } = useSupportCase(caseId);
  const {
    data: messagesData,
    isLoading: messagesLoading,
    refetch: refetchMessages,
  } = useCaseMessages(caseId);
  const addCommentMutation = useAddCaseComment(caseId);

  const [replyText, setReplyText] = useState("");
  const [pendingMessage, setPendingMessage] = useState<CaseMessage | null>(null);
  const [showSentConfirmation, setShowSentConfirmation] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const [lastViewedTime] = useState(() => getLastViewedTimestamp(caseId));

  useEffect(() => {
    setLastViewedTimestamp(caseId);
  }, [caseId]);

  const hasPendingMessage = pendingMessage !== null;
  useEffect(() => {
    if (messagesEndRef.current) messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
  }, [messagesData?.messages.length, hasPendingMessage]);

  const handleSubmitReply = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!replyText.trim() || addCommentMutation.isPending) return;
    const messageText = replyText.trim();
    const optimisticMsg: CaseMessage = {
      id: `pending-${Date.now()}`,
      type: "comment",
      body: messageText,
      author: { name: "You", email: null, isCustomer: true },
      createdAt: new Date().toISOString(),
      direction: null,
    };
    setPendingMessage(optimisticMsg);
    setReplyText("");
    try {
      await addCommentMutation.mutateAsync({ body: messageText });
      setShowSentConfirmation(true);
      setTimeout(() => setShowSentConfirmation(false), 2000);
    } catch {
      setReplyText(messageText);
    } finally {
      setPendingMessage(null);
    }
  };

  const showLoading = !supportCase && !error;
  const pageError =
    error && process.env.NODE_ENV !== "development"
      ? "Unable to load this case right now. Please try again."
      : error;
  const isCaseClosed = supportCase
    ? CLOSED_STATUSES.includes(supportCase.status as (typeof CLOSED_STATUSES)[number])
    : false;

  return {
    supportCase,
    error,
    refetch,
    showLoading,
    pageError,
    isCaseClosed,
    messagesData,
    messagesLoading,
    refetchMessages,
    addCommentMutation,
    replyText,
    setReplyText,
    pendingMessage,
    showSentConfirmation,
    messagesEndRef,
    lastViewedTime,
    handleSubmitReply,
  };
}

export function SupportCaseDetailView({ caseId }: SupportCaseDetailViewProps): React.ReactElement {
  const state = useCaseDetailState(caseId);

  if (!state.showLoading && !state.supportCase) {
    return <CaseNotFoundView />;
  }

  return (
    <PageLayout
      icon={<TicketIconSolid />}
      title={state.supportCase ? `Case #${state.supportCase.caseNumber}` : "Loading..."}
      loading={state.showLoading}
      error={state.pageError}
      onRetry={() => void state.refetch()}
      backLink={{ label: "Back to Cases", href: SUPPORT_HREF }}
      actions={
        <Button
          as="a"
          href={SUPPORT_HREF}
          variant="outline"
          leftIcon={<ArrowLeftIcon className="h-4 w-4" />}
        >
          All Cases
        </Button>
      }
    >
      {state.supportCase && (
        <div className="space-y-6">
          <CaseHeaderCard supportCase={state.supportCase} />
          <CaseConversationSection
            supportCase={state.supportCase}
            messagesData={state.messagesData}
            messagesLoading={state.messagesLoading}
            pendingMessage={state.pendingMessage}
            lastViewedTime={state.lastViewedTime}
            messagesEndRef={state.messagesEndRef}
            showSentConfirmation={state.showSentConfirmation}
            isCaseClosed={state.isCaseClosed}
            replyText={state.replyText}
            setReplyText={state.setReplyText}
            addCommentMutation={state.addCommentMutation}
            handleSubmitReply={state.handleSubmitReply}
            refetchMessages={state.refetchMessages}
          />
        </div>
      )}
    </PageLayout>
  );
}

// ============================================================================
// Case Detail Sub-Components
// ============================================================================

function CaseNotFoundView(): React.ReactElement {
  return (
    <PageLayout
      icon={<TicketIconSolid />}
      title="Case Not Found"
      backLink={{ label: "Back to Cases", href: SUPPORT_HREF }}
    >
      <AlertBanner variant="error" title="Case not found">
        The support case you&apos;re looking for could not be found or you don&apos;t have
        permission to view it.
      </AlertBanner>
    </PageLayout>
  );
}

function CaseHeaderCard({ supportCase }: { supportCase: SupportCase }): React.ReactElement {
  return (
    <div className="border border-border rounded-xl bg-card overflow-hidden shadow-[var(--cp-shadow-1)]">
      <div className="p-5 border-b border-border">
        <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
          <div className="flex items-start gap-3">
            <div className="mt-0.5">{getCaseStatusIcon(supportCase.status, "md")}</div>
            <div>
              <h2 className="text-lg font-semibold text-foreground leading-snug">
                {supportCase.subject}
              </h2>
              <p className="text-sm text-muted-foreground mt-0.5">Case #{supportCase.caseNumber}</p>
            </div>
          </div>
          <div className="flex flex-wrap gap-2">
            <span
              className={`inline-flex items-center px-3 py-1 rounded-lg text-sm font-medium ${getCaseStatusClasses(supportCase.status)}`}
            >
              {supportCase.status}
            </span>
            <span
              className={`inline-flex items-center px-3 py-1 rounded-lg text-sm font-medium ${getCasePriorityClasses(supportCase.priority)}`}
            >
              {supportCase.priority}
            </span>
          </div>
        </div>
      </div>
      <CaseMetaInfoRow supportCase={supportCase} />
    </div>
  );
}

function CaseMetaInfoRow({ supportCase }: { supportCase: SupportCase }): React.ReactElement {
  return (
    <div className="px-5 py-3 bg-muted/40 flex flex-wrap items-center gap-x-6 gap-y-2 text-sm">
      <div className="flex items-center gap-2 text-muted-foreground">
        <CalendarIcon className="h-4 w-4 text-muted-foreground/70" />
        <span>Created {formatIsoDate(supportCase.createdAt)}</span>
      </div>
      <div className="flex items-center gap-2 text-muted-foreground">
        <ClockIcon className="h-4 w-4 text-muted-foreground/70" />
        <span>Updated {formatIsoRelative(supportCase.updatedAt)}</span>
      </div>
      {supportCase.category && (
        <div className="flex items-center gap-2 text-muted-foreground">
          <TagIcon className="h-4 w-4 text-muted-foreground/70" />
          <span>{supportCase.category}</span>
        </div>
      )}
      {supportCase.closedAt && (
        <div className="flex items-center gap-2 text-success">
          <span>Closed {formatIsoDate(supportCase.closedAt)}</span>
        </div>
      )}
    </div>
  );
}

interface CaseConversationSectionProps {
  supportCase: SupportCase;
  messagesData: { messages: CaseMessage[] } | undefined;
  messagesLoading: boolean;
  pendingMessage: CaseMessage | null;
  lastViewedTime: string | null;
  messagesEndRef: React.RefObject<HTMLDivElement | null>;
  showSentConfirmation: boolean;
  isCaseClosed: boolean;
  replyText: string;
  setReplyText: (text: string) => void;
  addCommentMutation: ReturnType<typeof useAddCaseComment>;
  handleSubmitReply: (e: React.FormEvent) => Promise<void>;
  refetchMessages: () => void;
}

function CaseConversationSection({
  supportCase,
  messagesData,
  messagesLoading,
  pendingMessage,
  lastViewedTime,
  messagesEndRef,
  showSentConfirmation,
  isCaseClosed,
  replyText,
  setReplyText,
  addCommentMutation,
  handleSubmitReply,
  refetchMessages,
}: CaseConversationSectionProps): React.ReactElement {
  return (
    <div className="border border-border rounded-xl bg-card overflow-hidden shadow-[var(--cp-shadow-1)]">
      <div className="px-5 py-3 border-b border-border flex items-center justify-between">
        <h3 className="text-sm font-semibold text-foreground">Conversation</h3>
        <button
          type="button"
          onClick={() => void refetchMessages()}
          className="text-xs text-muted-foreground hover:text-foreground transition-colors"
        >
          Refresh
        </button>
      </div>

      <ConversationThread
        supportCase={supportCase}
        messagesData={messagesData}
        messagesLoading={messagesLoading}
        pendingMessage={pendingMessage}
        lastViewedTime={lastViewedTime}
        messagesEndRef={messagesEndRef}
        showSentConfirmation={showSentConfirmation}
      />

      {!isCaseClosed && (
        <ReplyForm
          replyText={replyText}
          setReplyText={setReplyText}
          addCommentMutation={addCommentMutation}
          handleSubmitReply={handleSubmitReply}
        />
      )}

      {isCaseClosed && <ClosedCaseNotice />}
    </div>
  );
}

interface ReplyFormProps {
  replyText: string;
  setReplyText: (text: string) => void;
  addCommentMutation: ReturnType<typeof useAddCaseComment>;
  handleSubmitReply: (e: React.FormEvent) => Promise<void>;
}

function ReplyForm({
  replyText,
  setReplyText,
  addCommentMutation,
  handleSubmitReply,
}: ReplyFormProps): React.ReactElement {
  return (
    <div className="px-5 py-4 border-t border-border bg-muted/20">
      <form onSubmit={handleSubmitReply}>
        <div className="space-y-3">
          <textarea
            value={replyText}
            onChange={e => setReplyText(e.target.value)}
            placeholder="Type your reply..."
            rows={3}
            className="w-full px-4 py-3 rounded-lg border border-border bg-background text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary resize-none"
            disabled={addCommentMutation.isPending}
          />
          <div className="flex items-center justify-between">
            <p className="text-xs text-muted-foreground">
              Your reply will be visible to our support team.
            </p>
            <Button
              type="submit"
              disabled={!replyText.trim() || addCommentMutation.isPending}
              leftIcon={
                addCommentMutation.isPending ? (
                  <Spinner size="sm" />
                ) : (
                  <PaperAirplaneIcon className="h-4 w-4" />
                )
              }
            >
              {addCommentMutation.isPending ? "Sending..." : "Send Reply"}
            </Button>
          </div>
          {addCommentMutation.isError && (
            <p className="text-sm text-destructive">Failed to send reply. Please try again.</p>
          )}
        </div>
      </form>
    </div>
  );
}

function ClosedCaseNotice(): React.ReactElement {
  return (
    <div className="px-5 py-4 border-t border-border bg-muted/20">
      <p className="text-sm text-muted-foreground text-center">
        This case is closed. If you need further assistance, please{" "}
        <a href="/account/support/new" className="text-primary hover:underline">
          create a new case
        </a>
        .
      </p>
    </div>
  );
}

// ============================================================================
// Conversation Components
// ============================================================================

interface ConversationThreadProps {
  supportCase: {
    description: string;
    createdAt: string;
  };
  messagesData: { messages: CaseMessage[] } | undefined;
  messagesLoading: boolean;
  pendingMessage: CaseMessage | null;
  lastViewedTime: string | null;
  messagesEndRef: React.RefObject<HTMLDivElement | null>;
  showSentConfirmation: boolean;
}

/**
 * Conversation thread with date grouping and sender grouping
 */
function ConversationThread({
  supportCase,
  messagesData,
  messagesLoading,
  pendingMessage,
  lastViewedTime,
  messagesEndRef,
  showSentConfirmation,
}: ConversationThreadProps) {
  // Create initial description message
  const descriptionMessage: CaseMessage = useMemo(
    () => ({
      id: "description",
      type: "comment",
      body: supportCase.description,
      author: { name: "You", email: null, isCustomer: true },
      createdAt: supportCase.createdAt,
      direction: null,
    }),
    [supportCase.description, supportCase.createdAt]
  );

  // Combine description with messages, add pending if exists, and group by date
  const messageGroups = useMemo(() => {
    const allMessages = [
      descriptionMessage,
      ...(messagesData?.messages ?? []),
      ...(pendingMessage ? [pendingMessage] : []),
    ];
    return groupMessagesByDate(allMessages);
  }, [descriptionMessage, messagesData?.messages, pendingMessage]);

  if (messagesLoading) {
    return (
      <div className="p-5 flex items-center justify-center py-8">
        <Spinner size="md" />
      </div>
    );
  }

  const hasReplies = (messagesData?.messages?.length ?? 0) > 0;

  return (
    <div className="p-5">
      <div className="space-y-6">
        {messageGroups.map(group => {
          // Group consecutive messages within this date group
          const senderGroups = groupConsecutiveMessages(group.messages);

          return (
            <div key={group.date}>
              {/* Date separator */}
              <div className="flex items-center gap-3 mb-4">
                <div className="flex-1 h-px bg-border" />
                <span className="text-xs font-medium text-muted-foreground px-2">
                  {group.dateLabel}
                </span>
                <div className="flex-1 h-px bg-border" />
              </div>

              {/* Messages for this date, grouped by sender */}
              <div className="space-y-4">
                {senderGroups.map((senderGroup, groupIndex) => (
                  <MessageGroupBubbles
                    key={`${senderGroup.senderId}-${groupIndex}`}
                    senderGroup={senderGroup}
                    pendingMessageId={pendingMessage?.id ?? null}
                    lastViewedTime={lastViewedTime}
                    showSentConfirmation={
                      showSentConfirmation && groupIndex === senderGroups.length - 1
                    }
                  />
                ))}
              </div>
            </div>
          );
        })}

        {/* No replies yet message */}
        {!hasReplies && (
          <div className="text-center py-6">
            <ChatBubbleLeftRightIcon className="h-10 w-10 text-muted-foreground/40 mx-auto mb-3" />
            <p className="text-sm text-muted-foreground">
              Your message has been received! Our support team typically responds within 24 hours.
            </p>
          </div>
        )}

        {/* Auto-scroll anchor */}
        <div ref={messagesEndRef} />
      </div>
    </div>
  );
}

/**
 * Grouped messages from the same sender - shows avatar only on first message
 */
function MessageGroupBubbles({
  senderGroup,
  pendingMessageId,
  lastViewedTime,
  showSentConfirmation,
}: {
  senderGroup: SenderMessageGroup;
  pendingMessageId: string | null;
  lastViewedTime: string | null;
  showSentConfirmation: boolean;
}) {
  const { isCustomer, messages } = senderGroup;

  return (
    <div className={`flex gap-2 ${isCustomer ? "justify-end" : "justify-start"}`}>
      {/* Avatar - only show for support (on left side) */}
      {!isCustomer && (
        <div className="flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center bg-muted text-muted-foreground mt-1">
          <ChatBubbleLeftRightIcon className="w-4 h-4" />
        </div>
      )}

      {/* Message bubbles */}
      <div
        className={`flex flex-col gap-1 max-w-[85%] ${isCustomer ? "items-end" : "items-start"}`}
      >
        {messages.map((message, index) => {
          const isFirst = index === 0;
          const isLast = index === messages.length - 1;
          const isPending = message.id === pendingMessageId;
          const isNew = Boolean(
            !isCustomer && lastViewedTime && new Date(message.createdAt) > new Date(lastViewedTime)
          );

          return (
            <MessageBubble
              key={message.id}
              message={message}
              showHeader={isFirst}
              isPending={isPending}
              isNew={isNew}
              showSentConfirmation={showSentConfirmation && isLast && isCustomer}
            />
          );
        })}
      </div>

      {/* Avatar - only show for customer (on right side) */}
      {isCustomer && (
        <div className="flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center bg-primary/10 text-primary mt-1">
          <UserIcon className="w-4 h-4" />
        </div>
      )}
    </div>
  );
}

/**
 * Message bubble component for displaying individual messages
 */
function MessageBubble({
  message,
  showHeader = true,
  isPending = false,
  isNew = false,
  showSentConfirmation = false,
}: {
  message: CaseMessage;
  showHeader?: boolean;
  isPending?: boolean;
  isNew?: boolean;
  showSentConfirmation?: boolean;
}): React.ReactElement {
  const isCustomer = message.author.isCustomer;
  const bubbleClasses = isCustomer
    ? "bg-primary text-primary-foreground rounded-br-md"
    : "bg-muted text-foreground rounded-bl-md";
  const headerColorClass = isCustomer ? AUTHOR_COLOR_MUTED : "text-muted-foreground";

  return (
    <div
      className={`rounded-2xl px-4 py-3 shadow-sm ${bubbleClasses} ${isPending ? "opacity-70" : ""}`}
    >
      {showHeader && (
        <MessageBubbleHeader message={message} isNew={isNew} headerColorClass={headerColorClass} />
      )}
      <p className="whitespace-pre-wrap text-sm leading-relaxed">{message.body}</p>
      <MessageBubbleStatus
        isPending={isPending}
        showSentConfirmation={showSentConfirmation}
        isCustomer={isCustomer}
      />
    </div>
  );
}

function MessageBubbleHeader({
  message,
  isNew,
  headerColorClass,
}: {
  message: CaseMessage;
  isNew: boolean;
  headerColorClass: string;
}): React.ReactElement {
  const isEmail = message.type === "email";
  const hasAttachment = message.hasAttachment === true;
  const displayName = message.author.isCustomer ? "You" : message.author.name;

  return (
    <div className={`flex items-center gap-2 mb-1 text-xs ${headerColorClass}`}>
      {isEmail ? <EnvelopeIcon className="h-3 w-3" /> : <ChatBubbleLeftIcon className="h-3 w-3" />}
      <span className="font-medium">{displayName}</span>
      <span>-</span>
      <span>{formatIsoRelative(message.createdAt)}</span>
      {hasAttachment && (
        <>
          <span>-</span>
          <span className="inline-flex items-center gap-1">
            <PaperClipIcon className="h-3 w-3" />
            Attachment
          </span>
        </>
      )}
      {isNew && (
        <span className="ml-1 px-1.5 py-0.5 rounded bg-primary text-primary-foreground text-[10px] font-semibold uppercase">
          New
        </span>
      )}
    </div>
  );
}

function MessageBubbleStatus({
  isPending,
  showSentConfirmation,
  isCustomer,
}: {
  isPending: boolean;
  showSentConfirmation: boolean;
  isCustomer: boolean;
}): React.ReactElement | null {
  const statusColorClass = isCustomer ? "text-primary-foreground/60" : "text-muted-foreground";

  if (isPending) {
    return (
      <div className={`flex items-center gap-1 mt-1 text-xs ${statusColorClass}`}>
        <Spinner size="xs" />
        <span>Sending...</span>
      </div>
    );
  }

  if (showSentConfirmation) {
    return (
      <div className={`flex items-center gap-1 mt-1 text-xs ${statusColorClass} animate-fade-in`}>
        <CheckIcon className="h-3 w-3" />
        <span>Sent</span>
      </div>
    );
  }

  return null;
}
