import { cn } from '@/lib/utils';
import { useAuthStore } from '@/stores/authStore';
import { useSocketStore } from '@/stores/socketStore';
import type { Message, MessageReaction } from '@/types';
import { Heart, Smile, ThumbsUp, Trash2 } from 'lucide-react';
import { useMemo, useRef, useState, type FC } from 'react';
import { toast } from 'sonner';
import { Button } from './ui/button';
import { Popover, PopoverContent, PopoverTrigger } from './ui/popover';

export const MessageCard: FC<{ message: Message }> = ({ message }) => {
  const { user } = useAuthStore();
  const { socket } = useSocketStore();
  const [showReactions, setShowReactions] = useState(false);
  const longPressTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const isCurrentUser = message.userId === user?.id;

  const handleReaction = (messageId: string, type: string) => {
    if (socket) {
      socket.emit('react_to_message', {
        messageId,
        type,
      });
    }
  };

  const hasUserReacted = (reactions: MessageReaction[], type: string) => {
    return reactions.some((r) => r.type === type && r.userId === user?.id);
  };

  const handleDeleteMessage = () => {
    if (confirm('Are you sure you want to delete this message?')) {
      if (socket) {
        socket.emit('delete_message', {
          messageId: message.id,
          roomId: message.roomId,
        });
        setShowReactions(false);
        toast.info('Message deleted successfully');
      }
    }
  };

  const formatTime = (dateString: string) => {
    return new Date(dateString).toLocaleTimeString([], {
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const handleMouseDown = () => {
    longPressTimeoutRef.current = setTimeout(() => {
      setShowReactions(true);
    }, 500);
  };

  const handleMouseUp = () => {
    if (longPressTimeoutRef.current) {
      clearTimeout(longPressTimeoutRef.current);
      longPressTimeoutRef.current = null;
    }
  };

  const reactionGroups = message.reactions.reduce(
    (acc, reaction) => {
      if (!acc[reaction.type]) {
        acc[reaction.type] = 0;
      }
      acc[reaction.type]++;
      return acc;
    },
    {} as Record<string, number>
  );

  const messageStatus = useMemo(() => {
    if (!isCurrentUser) return null;

    if ((message.seenBy ?? []).length > 0) {
      return (
        <div className="text-xs text-gray-400 px-2">
          Seen{' '}
          {(message.seenBy ?? []).length > 1
            ? `by ${(message.seenBy ?? []).length}`
            : ''}
        </div>
      );
    }

    return <div className="text-xs text-gray-400 px-2">Delivered</div>;
  }, [isCurrentUser, message.seenBy]);

  return (
    <div
      className={cn(
        'flex flex-col gap-1 mb-3',
        isCurrentUser ? 'items-end' : 'items-start'
      )}
    >
      {!isCurrentUser && (
        <div className="text-xs font-medium ml-4 text-gray-600 dark:text-gray-300">
          {message.user.username}
        </div>
      )}

      <div className="flex relative group">
        <Popover open={showReactions} onOpenChange={setShowReactions}>
          <PopoverTrigger asChild>
            <div
              className={cn(
                'px-4 py-2 rounded-2xl relative cursor-pointer',
                isCurrentUser
                  ? 'bg-blue-500 text-white rounded-tr-none'
                  : 'bg-gray-100 text-gray-900 rounded-tl-none'
              )}
              onMouseDown={handleMouseDown}
              onMouseUp={handleMouseUp}
              onMouseLeave={handleMouseUp}
              onTouchStart={handleMouseDown}
              onTouchEnd={handleMouseUp}
            >
              {message.image && (
                <div className="mb-2 max-w-xs lg:max-w-md overflow-hidden rounded-lg">
                  <img
                    src={message.image}
                    alt="Message attachment"
                    className="max-w-full object-contain rounded-lg"
                  />
                </div>
              )}
              <div className="break-words max-w-xs lg:max-w-md">
                {message.content}
              </div>
            </div>
          </PopoverTrigger>
          <PopoverContent
            className="w-auto p-2 flex gap-2"
            align={isCurrentUser ? 'end' : 'start'}
            side="top"
            sideOffset={5}
          >
            <Button
              size="sm"
              variant="ghost"
              className="rounded-full p-2"
              onClick={() => {
                handleReaction(message.id, 'like');
                setShowReactions(false);
              }}
            >
              <Heart className="h-5 w-5 text-red-500" />
            </Button>
            <Button
              size="sm"
              variant="ghost"
              className="rounded-full p-2"
              onClick={() => {
                handleReaction(message.id, 'thumbs_up');
                setShowReactions(false);
              }}
            >
              <ThumbsUp className="h-5 w-5 text-blue-500" />
            </Button>
            <Button
              size="sm"
              variant="ghost"
              className="rounded-full p-2"
              onClick={() => {
                handleReaction(message.id, 'laugh');
                setShowReactions(false);
              }}
            >
              <Smile className="h-5 w-5 text-yellow-500" />
            </Button>
            {isCurrentUser && (
              <Button
                size="sm"
                variant="ghost"
                className="rounded-full p-2"
                onClick={handleDeleteMessage}
              >
                <Trash2 className="h-5 w-5 text-gray-500" />
              </Button>
            )}
          </PopoverContent>
        </Popover>
      </div>

      <div className="text-xs text-gray-500 px-2 dark:text-gray-400">
        {formatTime(message.createdAt)}
      </div>
      {messageStatus}
      {Object.keys(reactionGroups).length > 0 && (
        <div className="flex gap-1 mt-1">
          {Object.entries(reactionGroups).map(([type, count]) => (
            <div
              key={type}
              className={cn(
                'flex items-center gap-1 text-xs px-2 py-1 rounded-full',
                hasUserReacted(message.reactions, type)
                  ? type === 'like'
                    ? 'bg-red-100 dark:bg-red-900/20'
                    : type === 'thumbs_up'
                      ? 'bg-blue-100 dark:bg-blue-900/20'
                      : 'bg-yellow-100 dark:bg-yellow-900/20'
                  : 'bg-gray-100 dark:bg-gray-700'
              )}
              onClick={() => handleReaction(message.id, type)}
            >
              {type === 'like' && (
                <Heart
                  className={cn(
                    'h-3 w-3',
                    hasUserReacted(message.reactions, type)
                      ? 'fill-red-500 text-red-500'
                      : 'text-gray-600 dark:text-gray-300'
                  )}
                />
              )}
              {type === 'thumbs_up' && (
                <ThumbsUp
                  className={cn(
                    'h-3 w-3',
                    hasUserReacted(message.reactions, type)
                      ? 'fill-blue-500 text-blue-500'
                      : 'text-gray-600 dark:text-gray-300'
                  )}
                />
              )}
              {type === 'laugh' && (
                <Smile
                  className={cn(
                    'h-3 w-3',
                    hasUserReacted(message.reactions, type)
                      ? 'text-yellow-500'
                      : 'text-gray-600 dark:text-gray-300'
                  )}
                />
              )}
              <span className="text-gray-600 dark:text-gray-300">{count}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};
