import React, { useEffect, useRef, useMemo } from 'react';
import { useChatStore } from '../store/chatStore';
import { useUser } from '@/features/auth/hooks/useUser';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { sanitizeChatMessage } from '@/utils/sanitize';
import {
  MoreVertical,
  Reply,
  Smile,
  ThumbsUp,
  ThumbsDown,
  MessageSquare,
} from 'lucide-react';

function formatMessageDate(dateStr: string): string {
  const date = new Date(dateStr);
  const now = new Date();
  const diffDays = Math.floor(
    (now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24)
  );

  if (diffDays === 0) return 'Today';
  if (diffDays === 1) return 'Yesterday';

  return date.toLocaleDateString('en-US', {
    weekday: 'long',
    month: 'long',
    day: 'numeric',
  });
}

function DateSeparator({ date }: { date: string }) {
  const formatted = formatMessageDate(date);
  return (
    <div className="flex items-center gap-3 py-3">
      <div className="flex-1 h-px bg-border" />
      <span className="text-caption shrink-0 px-2">{formatted}</span>
      <div className="flex-1 h-px bg-border" />
    </div>
  );
}

export function ChatMessages() {
  const { currentConversationId, conversations, messages, typingUsers } = useChatStore();
  const { data: user } = useUser();
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // Action 4.5.1.5: Get current conversation from conversations array using ID
  const currentConversation = useMemo(() => {
    if (!currentConversationId) return null;
    return conversations.find((c) => c.id === currentConversationId) || null;
  }, [currentConversationId, conversations]);

  const conversationMessages = currentConversationId
    ? messages[currentConversationId] || []
    : [];

  const typingUserIds = currentConversationId
    ? typingUsers[currentConversationId] || []
    : [];

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [conversationMessages]);

  if (!currentConversation) {
    return (
      <div className="flex-1 flex items-center justify-center bg-muted/50">
        <div className="text-center">
          <MessageSquare className="h-12 w-12 mx-auto mb-4 text-muted-foreground" />
          <h3 className="text-lg font-medium text-muted-foreground">
            Sélectionnez une conversation
          </h3>
          <p className="text-sm text-muted-foreground">
            Choisissez une conversation pour commencer à discuter
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex-1 flex flex-col">
      {/* En-tête de la conversation */}
      <div className="p-4 border-b bg-background">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="font-semibold">
              {currentConversation.name ||
                `Conversation ${currentConversation.id.slice(0, 8)}`}
            </h3>
            <p className="text-sm text-muted-foreground">
              {currentConversation.participants?.length || 0} participant
              {(currentConversation.participants?.length || 0) > 1 ? 's' : ''}
            </p>
          </div>
          <Button variant="ghost" size="icon">
            <MoreVertical className="h-4 w-4" />
          </Button>
        </div>
      </div>

      {/* Messages */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {conversationMessages.length === 0 ? (
          <div className="text-center text-muted-foreground">
            <p>Aucun message dans cette conversation</p>
          </div>
        ) : (
          conversationMessages.map((message, index) => {
            const isOwn = message.sender_id === user?.id;
            const prevMessage = index > 0 ? conversationMessages[index - 1] : null;
            const showDateSeparator =
              !prevMessage ||
              new Date(message.created_at).toDateString() !==
                new Date(prevMessage.created_at).toDateString();

            return (
              <React.Fragment key={message.id}>
                {showDateSeparator && (
                  <DateSeparator date={message.created_at} />
                )}
                <div
                  className={`flex ${isOwn ? 'justify-end' : 'justify-start'}`}
                >
                  <div className={`max-w-[70%] ${isOwn ? 'order-2' : 'order-1'}`}>
                    <div className="flex items-center space-x-2 mb-1">
                      <span className="text-xs text-muted-foreground">
                        {isOwn ? 'Vous' : `Utilisateur ${message.sender_id}`}
                      </span>
                      <span className="text-xs text-muted-foreground">
                        {new Date(message.created_at).toLocaleTimeString([], {
                          hour: '2-digit',
                          minute: '2-digit',
                        })}
                      </span>
                    </div>
                    <Card
                      className={`${isOwn ? 'bg-primary text-primary-foreground' : ''}`}
                    >
                      <CardContent className="p-4">
                        <p
                          className="text-sm"
                          dangerouslySetInnerHTML={{
                            __html: sanitizeChatMessage(message.content),
                          }}
                        />

                        {/* Réactions */}
                        {message.reactions && Object.keys(message.reactions).length > 0 && (
                          <div className="flex flex-wrap gap-1 mt-2">
                            {Object.entries(message.reactions).map(([emoji, userIds]) => (
                              <Button
                                key={emoji}
                                variant="ghost"
                                size="sm"
                                className="h-6 px-2 text-xs"
                              >
                                {emoji} {userIds.length}
                              </Button>
                            ))}
                          </div>
                        )}
                      </CardContent>
                    </Card>

                    {/* Actions sur le message */}
                    <div className="flex items-center space-x-1 mt-1 opacity-0 group-hover:opacity-100 transition-opacity">
                      <Button variant="ghost" size="sm" className="h-6 px-2">
                        <ThumbsUp className="h-3 w-3" />
                      </Button>
                      <Button variant="ghost" size="sm" className="h-6 px-2">
                        <ThumbsDown className="h-3 w-3" />
                      </Button>
                      <Button variant="ghost" size="sm" className="h-6 px-2">
                        <Reply className="h-3 w-3" />
                      </Button>
                      <Button variant="ghost" size="sm" className="h-6 px-2">
                        <Smile className="h-3 w-3" />
                      </Button>
                    </div>
                  </div>
                </div>
              </React.Fragment>
            );
          })
        )}

        {/* Indicateur de frappe */}
        {typingUserIds.length > 0 && (
          <div className="flex items-center space-x-2 text-sm text-muted-foreground">
            <div className="flex space-x-1">
              <div className="w-2 h-2 bg-muted-foreground rounded-full animate-bounce"></div>
              <div
                className="w-2 h-2 bg-muted-foreground rounded-full animate-bounce"
                style={{ animationDelay: '0.1s' }}
              ></div>
              <div
                className="w-2 h-2 bg-muted-foreground rounded-full animate-bounce"
                style={{ animationDelay: '0.2s' }}
              ></div>
            </div>
            <span>
              {typingUserIds.length === 1
                ? "Quelqu'un"
                : `${typingUserIds.length} personnes`}{' '}
              est en train d'écrire...
            </span>
          </div>
        )}

        <div ref={messagesEndRef} />
      </div>
    </div>
  );
}
