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 } from '@/components/ui/avatar';
// Separator unused, removing
import { useAuthStore } from '@/features/auth/store/authStore';
// TODO: wsService should be replaced with websocketService or a proper chat service
import { wsService } from '@/services/websocket';
import { apiClient } from '@/services/api/client';
import { logger } from '@/utils/logger';
import { useToast } from '@/hooks/useToast';
import { ChatMessage, ChatStats } from '@/types';
import {
  Send,
  MessageCircle,
  Users,
  Wifi,
  WifiOff,
  Loader2,
  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 { success: showSuccess, error: showError } = useToast();
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const [isConnected, setIsConnected] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isSending, setIsSending] = useState(false);
  const [chatStats, setChatStats] = useState<ChatStats | null>(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);
      showSuccess('Chat connecté');
    };

    const handleChatDisconnected = () => {
      setIsConnected(false);
      showError('Connexion au chat perdue');
    };

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

    const handleChatError = (error: any) => {
      logger.error('Erreur chat:', { error });
      showError('Une erreur est survenue dans le chat');
    };

    // 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 apiClient.get<{ data: ChatMessage[] }>('/messages', {
        params: { conversation_id: room, limit: 50 },
      });
      // apiClient unwrap déjà le format { success, data }
      const data = response.data;
      setMessages(data.data || []);
    } catch (error) {
      logger.error('Erreur lors du chargement des messages:', { error });
    } finally {
      setIsLoading(false);
    }
  };

  const loadChatStats = async () => {
    try {
      const response = await apiClient.get<{
        active_users: number;
        total_messages: number;
        rooms_active: number;
      }>('/chat/stats');
      // apiClient unwrap déjà le format { success, data }
      const data = response.data;
      setChatStats(data);
    } catch (error) {
      logger.error('Erreur lors du chargement des statistiques:', { error });
    }
  };

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

    setIsSending(true);
    try {
      // Envoyer via WebSocket
      wsService.sendMessage(room, newMessage.trim());

      // Aussi envoyer via API REST pour la persistance
      await apiClient.post('/messages', {
        conversation_id: room,
        content: newMessage.trim(),
      });

      setNewMessage('');
    } catch (error) {
      logger.error("Erreur lors de l'envoi du message:", { error });
      showError("Impossible d'envoyer le message");
    } 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 Header removed custom wrapper if CardHeader handles padding */}
      <Card className="rounded-b-none border-b">
        <CardHeader className="py-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' : 'error'}>
                {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 mr-2">
                  <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" className="h-8 w-8 p-0">
                <Settings className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </CardHeader>
      </Card>

      {/* Zone des messages */}
      <Card className="flex-1 rounded-none border-0 flex flex-col overflow-hidden">
        <CardContent className="p-0 flex-1 overflow-hidden relative">
          <div className="h-full overflow-auto 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
                      src={`/avatars/${message.sender_id}.jpg`}
                      fallback={(message.sender_id || '?').charAt(0).toUpperCase()}
                      size="sm"
                      className="h-8 w-8"
                    />
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center space-x-2">
                        <span className="font-medium text-sm">
                          {message.sender_id}
                        </span>
                        <span className="text-xs text-muted-foreground">
                          {formatTimestamp(message.created_at)}
                        </span>
                      </div>
                      <p className="text-sm mt-1 break-words">
                        {message.content}
                      </p>
                    </div>
                  </div>
                ))}
                <div ref={messagesEndRef} />
              </div>
            )}
          </div>
        </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>
  );
}
