"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";

interface Message {
  _id: string;
  msg: string;
  ts: string;
  u: {
    _id: string;
    username: string;
    name?: 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 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">
      <CardHeader className="flex flex-row items-center justify-between">
        <CardTitle>Parole Messages</CardTitle>
        <Button 
          variant="ghost" 
          size="icon"
          onClick={() => 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={() => fetchMessages(true)}
              className="mt-2"
            >
              Try Again
            </Button>
          </div>
        )}
        {!loading && !error && (
          <div className="space-y-4 max-h-[500px] 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="border-b pb-2">
                  <p className="font-medium">{message.u.name || message.u.username}</p>
                  <p className="text-sm whitespace-pre-wrap">{message.msg}</p>
                  <p className="text-xs text-muted-foreground">
                    {new Date(message.ts).toLocaleString()}
                  </p>
                </div>
              ))
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
} 