
import React, { useRef, useEffect } from "react";
import { Card } from "@/components/ui/card";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { format } from "date-fns";
import { FileText } from "lucide-react";

// Safe date formatter
const safeFormatDate = (dateString, formatStr) => {
  if (!dateString) return "";
  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return "";
    return format(date, formatStr);
  } catch {
    return "";
  }
};

export default function MessageThread({ messages, currentUserId }) {
  const messagesEndRef = useRef(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const getRoleColor = (role) => {
    const colors = {
      client: "bg-purple-100 text-purple-700",
      vendor: "bg-amber-100 text-amber-700",
      staff: "bg-blue-100 text-blue-700",
      admin: "bg-slate-100 text-slate-700"
    };
    return colors[role] || "bg-slate-100 text-slate-700";
  };

  return (
    <div className="flex flex-col space-y-4 p-4 overflow-y-auto max-h-[500px]">
      {messages.map((message) => {
        const isOwnMessage = message.sender_id === currentUserId || message.created_by === currentUserId;
        
        return (
          <div
            key={message.id}
            className={`flex ${isOwnMessage ? 'justify-end' : 'justify-start'}`}
          >
            <div className={`flex gap-3 max-w-[70%] ${isOwnMessage ? 'flex-row-reverse' : 'flex-row'}`}>
              <Avatar className="w-8 h-8 flex-shrink-0">
                <AvatarFallback className={`${getRoleColor(message.sender_role)} text-xs font-bold`}>
                  {message.sender_name?.charAt(0) || '?'}
                </AvatarFallback>
              </Avatar>
              
              <div className={`flex flex-col ${isOwnMessage ? 'items-end' : 'items-start'}`}>
                <div className="flex items-center gap-2 mb-1">
                  <span className="text-xs font-semibold text-slate-700">{message.sender_name}</span>
                  <Badge variant="outline" className={`text-xs ${getRoleColor(message.sender_role)}`}>
                    {message.sender_role}
                  </Badge>
                </div>
                
                <Card className={`p-3 ${isOwnMessage ? 'bg-[#0A39DF] text-white' : 'bg-white'}`}>
                  <p className="text-sm">{message.content}</p>
                  
                  {message.attachments && message.attachments.length > 0 && (
                    <div className="mt-2 space-y-1">
                      {message.attachments.map((attachment, idx) => (
                        <a
                          key={idx}
                          href={attachment.url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="flex items-center gap-2 text-xs hover:underline"
                        >
                          <FileText className="w-3 h-3" />
                          {attachment.name}
                        </a>
                      ))}
                    </div>
                  )}
                </Card>
                
                <span className="text-xs text-slate-500 mt-1">
                  {safeFormatDate(message.created_date, "MMM d, h:mm a")}
                </span>
              </div>
            </div>
          </div>
        );
      })}
      <div ref={messagesEndRef} />
    </div>
  );
}
