import { useContext, useState } from 'react';
import { Trash2 } from 'lucide-react';
import AttachmentPreview from './AttachmentPreview.tsx';
import { ChatMessagesProps } from '@/types/types.ts';
import { useChat } from '@/context/chat/useChat.ts';
import { AuthContext } from '@/utils/AuthProvider.tsx';
import { format, isToday, isYesterday, formatDistanceToNow } from 'date-fns';

type AnimatedMessageProps = {
  message: ChatMessagesProps;
  onDelete: (messageId: number) => void;
};

const MessageElement = ({ onDelete, message }: AnimatedMessageProps) => {
  const { user } = useContext(AuthContext);
  const { me, groupOwner } = useChat();
  const [isRemoving, setIsRemoving] = useState(false);

  const handleDelete = () => {
    setIsRemoving(true);
    setTimeout(() => {
      onDelete(message.message_id);
    }, 300);
  };

  const formatMessageDate = (date: Date) => {
    if (isToday(date)) {
      return `Today ${format(date, 'HH:mm')}`;
    }
    if (isYesterday(date)) {
      return `Yesterday ${format(date, 'HH:mm')}`;
    }
    return format(date, 'dd.MM.yyyy HH:mm');
  };

  const messageDate = new Date(message.sent_at);
  const formattedDate = formatMessageDate(messageDate);
  const fullDate = format(messageDate, 'dd.MM.yyyy HH:mm');
  const timeAgo = formatDistanceToNow(messageDate, {
    addSuffix: true,
  });

  const canDelete =
    me.isGroupOwner ||
    message.sender === user?.username ||
    (me.isGroupAdmin && me.isGroupOwner && message.sender_id !== groupOwner);

  return (
    <li
      className={`whitespace-pre-wrap ml-2 rounded-lg p-1 group hover:bg-zinc-900
      ${isRemoving ? 'transition-all duration-300 opacity-0 -translate-x-full' : 'opacity-100'}`}
    >
      <div className="flex items-center justify-between">
        <div className="max-w-full">
          <div className="flex items-baseline space-x-2">
            <span className="font-bold text-emerald-400">{message.sender}</span>
            <span
              className="text-gray-600 text-[11px] antialiased font-sans font-semibold"
              title={`${fullDate} (${timeAgo})`}
            >
              {formattedDate}
            </span>
          </div>
          <div className="text-gray-200 mt-1">{message.message}</div>
          {message.attachment_urls && message.attachment_urls.length > 0 && (
            <div className="mt-2 flex flex-col gap-2 max-w-full">
              {message.attachment_urls.map((url, index) => (
                <AttachmentPreview
                  key={`${message.message_id}-${index}`}
                  url={url}
                />
              ))}
            </div>
          )}
        </div>
        {canDelete && (
          <Trash2
            className="opacity-0 group-hover:opacity-100 h-5 w-5 ml-2 flex-shrink-0 cursor-pointer text-gray-400 hover:text-red-500 transition-colors duration-200"
            onClick={handleDelete}
          />
        )}
      </div>
    </li>
  );
};

export default MessageElement;
