"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RefreshCw } from "lucide-react";
import { useRouter } from "next/navigation";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";

interface Message {
  _id: string;
  msg: string;
  ts: string;
  u: {
    _id: string;
    username: string;
    name?: string;
  };
  roomName: string;
  roomType: 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 router = useRouter();

  const fetchMessages = async (isRefresh = false) => {
    try {
      if (isRefresh) {
        setRefreshing(true);
      }
      const response = await fetch('/api/rocket-chat/messages', {
        // Prevent caching
        cache: 'no-store',
        next: { revalidate: 0 },
      });
      
      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)) {
        setMessages(data.messages);
      } else {
        console.warn('Unexpected data format:', data);
        setMessages([]);
      }
      setError(null);
    } catch (err) {
      console.error('Error fetching messages:', err);
      setError(err instanceof Error ? err.message : 'Failed to fetch messages');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    fetchMessages();
    // Set up polling every 30 seconds
    const interval = setInterval(() => fetchMessages(), 30000);
    return () => clearInterval(interval);
  }, []);

  return (
    <Card 
      className="transition-transform duration-500 ease-in-out transform hover:scale-105 cursor-pointer bg-white/50 backdrop-blur-sm" 
      onClick={() => router.push('/parole')}
    >
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <CardTitle className="text-lg font-semibold">Talk mentions</CardTitle>
        <Button 
          variant="ghost" 
          size="icon"
          onClick={(e) => {
            e.stopPropagation();
            fetchMessages(true);
          }}
          disabled={refreshing}
          className={refreshing ? 'animate-spin' : ''}
        >
          <RefreshCw className="h-4 w-4" />
        </Button>
      </CardHeader>
      <CardContent>
        {loading && <p className="text-center text-muted-foreground">Loading messages...</p>}
        {error && (
          <div className="text-center">
            <p className="text-red-500">Error: {error}</p>
            <Button 
              variant="outline" 
              onClick={(e) => {
                e.stopPropagation();
                fetchMessages(true);
              }}
              className="mt-2"
            >
              Try Again
            </Button>
          </div>
        )}
        {!loading && !error && (
          <div className="space-y-3 max-h-[400px] overflow-y-auto">
            {messages.length === 0 ? (
              <p className="text-center text-muted-foreground">No messages found</p>
            ) : (
              messages.map((message) => (
                <div key={message._id} className="flex items-start space-x-3 hover:bg-gray-50 p-2 rounded-lg transition-colors">
                  <Avatar className="h-8 w-8">
                    <AvatarImage src={`https://ui-avatars.com/api/?name=${encodeURIComponent(message.u.name || message.u.username)}&background=random`} />
                    <AvatarFallback>{(message.u.name || message.u.username).substring(0, 2).toUpperCase()}</AvatarFallback>
                  </Avatar>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-baseline">
                      <p className="text-sm font-medium truncate">{message.u.name || message.u.username}</p>
                      <span className="ml-2 text-xs text-gray-500">
                        {new Date(message.ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                      </span>
                    </div>
                    <p className="text-sm text-gray-600 whitespace-pre-wrap line-clamp-2">{message.msg}</p>
                    {message.roomName && (
                      <p className="text-xs text-blue-500 mt-1">
                        in {message.roomName}
                      </p>
                    )}
                  </div>
                </div>
              ))
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
} 