"use client";

import { useEffect, useState, useRef } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RefreshCw, MessageSquare, Loader2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { signIn, useSession } from "next-auth/react";
import { useWidgetNotification } from "@/hooks/use-widget-notification";
import { useUnifiedRefresh } from "@/hooks/use-unified-refresh";
import { REFRESH_INTERVALS } from "@/lib/constants/refresh-intervals";
import { Badge } from "@/components/ui/badge";

interface Message {
  id: string;
  text: string;
  timestamp: string;
  rawTimestamp: string;
  roomName: string;
  roomType: string;
  sender: {
    _id: string;
    username: string;
    name: string;
    initials: string;
    color: string;
  };
  isOwnMessage: boolean;
  room: {
    id: string;
    type: string;
    name: string;
    isChannel: boolean;
    isPrivateGroup: boolean;
    isDirect: boolean;
    link: string;
  };
}

export function Parole() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [unreadCount, setUnreadCount] = useState<number>(0);
  const router = useRouter();
  const { data: session, status } = useSession();
  const { triggerNotification } = useWidgetNotification();
  const lastUnreadCountRef = useRef<number>(-1); // Initialize to -1 to detect first load
  const lastMessageIdsRef = useRef<Set<string>>(new Set());
  const isInitializedRef = useRef<boolean>(false);

  const fetchMessages = async (forceRefresh = false) => {
    // Only show loading spinner on initial load, not on auto-refresh
    if (!messages.length) {
      setLoading(true);
    }
    setRefreshing(true);
    setError(null);

    try {
      const response = await fetch('/api/rocket-chat/messages' + (forceRefresh ? '?refresh=true' : ''), {
        cache: 'no-store',
        next: { revalidate: 0 },
        credentials: 'include',
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to fetch messages');
      }

      const data = await response.json();
      if (Array.isArray(data.messages)) {
        // Utiliser le totalUnreadCount de l'API (plus fiable)
        const currentUnreadCount = data.totalUnreadCount || 0;
        const currentMessageIds = new Set(data.messages.map((m: any) => m.id));
        
        // Update unread count state for badge display
        setUnreadCount(currentUnreadCount);
        
        // Detect new messages by comparing IDs (more reliable than count)
        const newMessageIds = new Set(
          Array.from(currentMessageIds).filter((id: string) => !lastMessageIdsRef.current.has(id))
        );
        const hasNewMessages = newMessageIds.size > 0;
        
        // On initialise au premier chargement
        if (!isInitializedRef.current) {
          console.log('[Parole Widget] 💬 Initializing - storing existing message IDs without notifications', {
            messageCount: data.messages.length,
            unreadCount: currentUnreadCount,
          });
          lastMessageIdsRef.current = currentMessageIds;
          lastUnreadCountRef.current = currentUnreadCount;
          isInitializedRef.current = true;
        } else {
          // Update count if it changed
          if (currentUnreadCount !== lastUnreadCountRef.current) {
            lastUnreadCountRef.current = currentUnreadCount;
          }
        }
        
        // Always prepare notification items (messages, max 10)
        const notificationItems = data.messages
          .slice(0, 10)
          .map((msg: any) => ({
            id: msg.id,
            title: msg.sender.name || msg.sender.username,
            message: msg.text || msg.message || '',
            link: '/parole',
            timestamp: new Date(msg.rawTimestamp || msg.timestamp),
            metadata: {
              roomName: msg.roomName,
              roomType: msg.roomType,
            },
          }));

        // Always trigger notification update to keep count fresh in Redis
        // This ensures the count doesn't expire even if it hasn't changed
        await triggerNotification({
          source: 'rocketchat',
          count: currentUnreadCount,
          items: notificationItems,
        });

        // Dispatch event for Outlook-style notifications (for new messages detected by ID)
        if (hasNewMessages) {
          console.log('[Parole Widget] 💬 Dispatching new messages event', {
            newMessagesCount: newMessageIds.size,
            newMessageIds: Array.from(newMessageIds),
            previousCount: lastUnreadCountRef.current,
            currentCount: currentUnreadCount,
            previousMessageIds: Array.from(lastMessageIdsRef.current),
          });
          
          window.dispatchEvent(new CustomEvent('new-messages-detected', {
            detail: {
              messages: data.messages,
              previousCount: lastUnreadCountRef.current,
              currentCount: currentUnreadCount,
            }
          }));
        }
        
        // Always update lastMessageIdsRef to track current state
        lastMessageIdsRef.current = currentMessageIds;
        setMessages(data.messages);
      } else {
        console.warn('Unexpected data format:', data);
        setMessages([]);
      }
      setError(null);
    } catch (err) {
      console.error('Error fetching messages:', err);
      const errorMessage = err instanceof Error ? err.message : 'Failed to fetch messages';
      setError(errorMessage);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  // Initial fetch on mount
  useEffect(() => {
    if (status === 'authenticated') {
      fetchMessages(false); // Use cache on initial load
    }
  }, [status]);

  // Integrate unified refresh for automatic polling
  // Use forceRefresh=true to ensure we get the latest messages immediately
  const { refresh } = useUnifiedRefresh({
    resource: 'parole',
    interval: REFRESH_INTERVALS.PAROLE, // 30 seconds
    enabled: status === 'authenticated',
    onRefresh: async () => {
      // Use forceRefresh to bypass cache and get latest messages immediately
      await fetchMessages(true); // Force refresh to get new messages immediately
    },
    priority: 'high',
  });

  // Manual refresh handler (bypasses cache)
  const handleManualRefresh = async (e?: React.MouseEvent) => {
    if (e) {
      e.stopPropagation();
    }
    await fetchMessages(true); // Force refresh, bypass cache
  };

  if (status === 'loading') {
    return (
      <Card className="transition-transform duration-500 ease-in-out transform hover:scale-105 bg-white/95 backdrop-blur-sm border-0 shadow-lg h-full">
        <CardHeader className="flex flex-row items-center justify-between pb-2 border-b border-gray-100">
          <CardTitle className="text-lg font-semibold text-gray-800 flex items-center gap-2">
            <MessageSquare className="h-5 w-5 text-gray-600" />
            Parole
          </CardTitle>
        </CardHeader>
        <CardContent className="p-6">
          <p className="text-center text-gray-500">Loading...</p>
        </CardContent>
      </Card>
    );
  }

  if (status === 'unauthenticated' || (error && error.includes('Session expired'))) {
    return (
      <Card className="transition-transform duration-500 ease-in-out transform hover:scale-105 bg-white/95 backdrop-blur-sm border-0 shadow-lg h-full">
        <CardHeader className="flex flex-row items-center justify-between pb-2 border-b border-gray-100">
          <CardTitle className="text-lg font-semibold text-gray-800 flex items-center gap-2">
            <MessageSquare className="h-5 w-5 text-gray-600" />
            Parole
          </CardTitle>
        </CardHeader>
        <CardContent className="p-6">
          <div className="text-center">
            <p className="text-gray-500 mb-4">Please sign in to view messages</p>
            <Button 
              onClick={(e) => {
                e.stopPropagation();
                signIn('keycloak');
              }}
              variant="default"
              className="bg-blue-600 hover:bg-blue-700 text-white"
            >
              Sign In
            </Button>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card 
      className="transition-transform duration-500 ease-in-out transform hover:scale-105 bg-white/95 backdrop-blur-sm border-0 shadow-lg cursor-pointer w-full" 
      onClick={() => router.push('/parole')}
    >
      <CardHeader className="flex flex-row items-center justify-between pb-2 border-b border-gray-100">
        <CardTitle className="text-lg font-semibold text-gray-800 flex items-center gap-2">
          <MessageSquare className="h-5 w-5 text-gray-600" />
          Parole
          {unreadCount > 0 && (
            <Badge variant="destructive" className="ml-1 text-xs">
              {unreadCount}
            </Badge>
          )}
        </CardTitle>
        <Button 
          variant="ghost" 
          size="icon"
          onClick={handleManualRefresh}
          disabled={refreshing}
          className="h-7 w-7 p-0 hover:bg-gray-100/50 rounded-full"
        >
          <RefreshCw className={`h-3.5 w-3.5 text-gray-600 ${refreshing ? 'animate-spin' : ''}`} />
        </Button>
      </CardHeader>
      <CardContent className="p-4">
        {loading && messages.length === 0 ? (
          <div className="text-center py-6 flex flex-col items-center">
            <Loader2 className="h-6 w-6 animate-spin text-gray-400 mb-2" />
            <p className="text-gray-500">Chargement des messages...</p>
          </div>
        ) : error ? (
          <div className="text-center py-4">
            <p className="text-red-500 text-sm mb-2">{error}</p>
            <Button 
              variant="outline" 
              onClick={handleManualRefresh}
              className="mt-2"
            >
              Réessayer
            </Button>
          </div>
        ) : (
          <div className="space-y-4 max-h-[400px] overflow-y-auto pr-1 scrollbar-thin scrollbar-thumb-gray-200 scrollbar-track-transparent">
            {messages.length === 0 ? (
              <p className="text-center text-gray-500 py-6">Aucun message</p>
            ) : (
              messages.map((message) => (
                <div key={message.id} className="flex items-start space-x-3 hover:bg-gray-50/50 p-3 rounded-lg transition-colors">
                  <Avatar className="h-8 w-8" style={{ backgroundColor: message.sender.color }}>
                    <AvatarImage src={`https://ui-avatars.com/api/?name=${encodeURIComponent(message.sender.name)}&background=random`} />
                    <AvatarFallback>{message.sender.initials}</AvatarFallback>
                  </Avatar>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-baseline justify-between space-x-2">
                      <p className="text-sm font-semibold text-gray-800 truncate max-w-[70%]">{message.sender.name}</p>
                      <span className="text-xs font-medium text-gray-500 flex-shrink-0">{message.timestamp}</span>
                    </div>
                    <p className="text-sm text-gray-600 whitespace-pre-wrap line-clamp-2 mt-1">{message.text}</p>
                    {message.roomName && (
                      <div className="flex items-center mt-2">
                        <span className={`inline-flex items-center px-2 py-1 rounded-md text-xs font-medium ${
                          message.room.isChannel ? 'bg-blue-50 text-blue-700' :
                          message.room.isPrivateGroup ? 'bg-purple-50 text-purple-700' :
                          'bg-green-50 text-green-700'
                        }`}>
                          {message.room.isChannel ? '#' : message.room.isPrivateGroup ? '🔒' : '💬'} {message.roomName}
                        </span>
                      </div>
                    )}
                  </div>
                </div>
              ))
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
} 