import React, { useState, useEffect, useRef } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { ScrollArea } from '@/components/ui/scroll-area';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { Separator } from '@/components/ui/separator';
import { useAuthStore } from '@/stores/auth';
import { websocketService } from '@/services/websocket';
// TODO: wsService should be replaced with websocketService or a proper chat service
const wsService = websocketService as any;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import EmojiPicker, { EmojiClickData } from 'emoji-picker-react';
import { apiService } from '@/services/api';
import { toast } from '@/hooks/use-toast';
import { ChatMessage } from '@/types';
import { 
  Send, 
  MessageCircle, 
  Users, 
  Wifi, 
  WifiOff, 
  Loader2,
  // MoreVertical,
  Settings,
  Hash
} from 'lucide-react';

interface ChatInterfaceProps {
  room?: string;
  onRoomChange?: (room: string) => void;
}

export function ChatInterface({ room = 'general', onRoomChange: _onRoomChange }: ChatInterfaceProps) {
  const { user } = useAuthStore();
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const [isConnected, setIsConnected] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isSending, setIsSending] = useState(false);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [onlineUsers, setOnlineUsers] = useState<string[]>([]);
  const [chatStats, setChatStats] = useState<any>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // Auto-scroll vers le bas
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

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

  // Gestion des événements WebSocket
  useEffect(() => {
    const handleChatConnected = () => {
      setIsConnected(true);
      toast({
        title: 'Chat connecté',
        description: 'Vous êtes maintenant connecté au chat.',
      });
    };

    const handleChatDisconnected = () => {
      setIsConnected(false);
      toast({
        title: 'Chat déconnecté',
        description: 'Connexion au chat perdue.',
        variant: 'destructive',
      });
    };

    const handleChatMessage = (message: ChatMessage) => {
      setMessages(prev => [...prev, message]);
    };

    const handleChatError = (error: any) => {
      console.error('Erreur chat:', error);
      toast({
        title: 'Erreur chat',
        description: 'Une erreur est survenue dans le chat.',
        variant: 'destructive',
      });
    };

    // S'abonner aux événements
    wsService.on('chat_connected', handleChatConnected);
    wsService.on('chat_disconnected', handleChatDisconnected);
    wsService.on('chat_message', handleChatMessage);
    wsService.on('chat_error', handleChatError);

    // Se connecter au chat
    wsService.connectChat();
    if (room) {
      wsService.joinRoom(room);
    }

    // Charger les messages existants
    loadMessages();
    loadChatStats();

    return () => {
      wsService.off('chat_connected', handleChatConnected);
      wsService.off('chat_disconnected', handleChatDisconnected);
      wsService.off('chat_message', handleChatMessage);
      wsService.off('chat_error', handleChatError);
    };
  }, [room]);

  const loadMessages = async () => {
    setIsLoading(true);
    try {
      const response = await apiService.getChatMessages({ room, limit: 50 });
      if (response.success) {
        setMessages(response.data || []);
      }
    } catch (error) {
      console.error('Erreur lors du chargement des messages:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const loadChatStats = async () => {
    try {
      const response = await apiService.getChatStats();
      if (response.success) {
        setChatStats(response.data);
      }
    } catch (error) {
      console.error('Erreur lors du chargement des statistiques:', error);
    }
  };

  const handleSendMessage = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newMessage.trim() || !user || isSending) return;

    const messageData = {
      content: newMessage.trim(),
      author: user.username,
      room,
      is_direct: false,
    };

    setIsSending(true);
    try {
      // Envoyer via WebSocket
      wsService.sendMessage(messageData);
      
      // Aussi envoyer via API REST pour la persistance
      await apiService.sendChatMessage(messageData);
      
      setNewMessage('');
    } catch (error) {
      console.error('Erreur lors de l\'envoi du message:', error);
      toast({
        title: 'Erreur',
        description: 'Impossible d\'envoyer le message.',
        variant: 'destructive',
      });
    } finally {
      setIsSending(false);
    }
  };

  const formatTimestamp = (timestamp: string) => {
    const date = new Date(timestamp);
    return date.toLocaleTimeString('fr-FR', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  };

  return (
    <div className="flex flex-col h-full">
      {/* En-tête du chat */}
      <Card className="rounded-b-none">
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <div className="flex items-center space-x-2">
                <MessageCircle className="h-5 w-5" />
                <CardTitle className="text-lg">
                  <Hash className="h-4 w-4 inline mr-1" />
                  {room}
                </CardTitle>
              </div>
              <Badge variant={isConnected ? 'default' : 'destructive'}>
                {isConnected ? (
                  <>
                    <Wifi className="h-3 w-3 mr-1" />
                    Connecté
                  </>
                ) : (
                  <>
                    <WifiOff className="h-3 w-3 mr-1" />
                    Déconnecté
                  </>
                )}
              </Badge>
            </div>
            <div className="flex items-center space-x-2">
              {chatStats && (
                <div className="flex items-center space-x-4 text-sm text-muted-foreground">
                  <div className="flex items-center space-x-1">
                    <Users className="h-4 w-4" />
                    <span>{chatStats.active_users || 0}</span>
                  </div>
                  <div className="flex items-center space-x-1">
                    <MessageCircle className="h-4 w-4" />
                    <span>{chatStats.total_messages || 0}</span>
                  </div>
                </div>
              )}
              <Button variant="ghost" size="sm">
                <Settings className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </CardHeader>
      </Card>

      {/* Zone des messages */}
      <Card className="flex-1 rounded-none">
        <CardContent className="p-0 h-full">
          <ScrollArea className="h-full p-4">
            {isLoading ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="h-6 w-6 animate-spin" />
              </div>
            ) : messages.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <MessageCircle className="h-12 w-12 mx-auto mb-4 opacity-50" />
                <p>Aucun message dans ce salon</p>
                <p className="text-sm">Soyez le premier à écrire quelque chose !</p>
              </div>
            ) : (
              <div className="space-y-4">
                {messages.map((message, index) => (
                  <div key={message.id || index} className="flex space-x-3">
                    <Avatar className="h-8 w-8">
                      <AvatarImage src={`/avatars/${message.author}.jpg`} />
                      <AvatarFallback>
                        {message.author.charAt(0).toUpperCase()}
                      </AvatarFallback>
                    </Avatar>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center space-x-2">
                        <span className="font-medium text-sm">{message.author}</span>
                        <span className="text-xs text-muted-foreground">
                          {formatTimestamp(message.timestamp)}
                        </span>
                        {message.is_direct && (
                          <Badge variant="outline" className="text-xs">
                            Privé
                          </Badge>
                        )}
                      </div>
                      <p className="text-sm mt-1 break-words">{message.content}</p>
                    </div>
                  </div>
                ))}
                <div ref={messagesEndRef} />
              </div>
            )}
          </ScrollArea>
        </CardContent>
      </Card>

      {/* Zone de saisie */}
      <Card className="rounded-t-none">
        <CardContent className="p-4">
          <form onSubmit={handleSendMessage} className="flex space-x-2">
            <Input
              value={newMessage}
              onChange={(e) => setNewMessage(e.target.value)}
              placeholder={`Écrire dans #${room}...`}
              disabled={!isConnected || isSending}
              className="flex-1"
            />
            <Button 
              type="submit" 
              disabled={!newMessage.trim() || !isConnected || isSending}
              size="sm"
            >
              {isSending ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Send className="h-4 w-4" />
              )}
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
}
