import { format } from "date-fns";
import { ru } from "date-fns/locale";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import type { SupportMessage } from "@shared/schema";

interface MessageTimelineProps {
  messages: SupportMessage[];
}

export function MessageTimeline({ messages }: MessageTimelineProps) {
  const getInitials = (firstName: string, lastName: string) => {
    return `${firstName.charAt(0)}${lastName.charAt(0) || ""}`.toUpperCase();
  };

  if (messages.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-8 text-center">
        <p className="text-sm text-muted-foreground">
          Нет сообщений в истории
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {messages.map((message, index) => (
        <div
          key={message.id || index}
          className={cn(
            "flex gap-3",
            message.isAdmin ? "flex-row-reverse" : "flex-row"
          )}
        >
          <Avatar className="h-8 w-8 flex-shrink-0">
            <AvatarFallback className={cn(
              "text-xs",
              message.isAdmin && "bg-primary text-primary-foreground"
            )}>
              {message.isAdmin ? "A" : getInitials(message.odFirstName, message.odLastName)}
            </AvatarFallback>
          </Avatar>
          <div
            className={cn(
              "flex flex-col max-w-[70%]",
              message.isAdmin ? "items-end" : "items-start"
            )}
          >
            <div className="flex items-center gap-2 mb-1">
              <span className="text-xs font-medium">
                {message.isAdmin ? "Поддержка" : `${message.odFirstName} ${message.odLastName}`}
              </span>
              {message.isAdmin && (
                <Badge variant="secondary" className="text-[10px] px-1.5 py-0">
                  Админ
                </Badge>
              )}
            </div>
            <div
              className={cn(
                "rounded-lg px-4 py-2",
                message.isAdmin
                  ? "bg-primary text-primary-foreground"
                  : "bg-muted"
              )}
            >
              <p className="text-sm whitespace-pre-wrap break-words">
                {message.text}
              </p>
            </div>
            <span className="text-[10px] text-muted-foreground mt-1 font-mono">
              {format(new Date(message.timestamp * 1000), "dd MMM yyyy, HH:mm", {
                locale: ru,
              })}
            </span>
          </div>
        </div>
      ))}
    </div>
  );
}
