"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

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

  useEffect(() => {
    const fetchMessages = async () => {
      try {
        // First, login to get auth token
        const loginResponse = await fetch('https://parole.slm-lab.net/api/v1/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            user: process.env.NEXT_PUBLIC_ROCKET_CHAT_USER,
            password: process.env.NEXT_PUBLIC_ROCKET_CHAT_PASSWORD,
          }),
        });

        if (!loginResponse.ok) {
          throw new Error('Failed to authenticate with RocketChat');
        }

        const { data: authData } = await loginResponse.json();

        // Then fetch messages using the auth token
        const messagesResponse = await fetch('https://parole.slm-lab.net/api/v1/channels.messages?roomName=general', {
          headers: {
            'X-Auth-Token': authData.authToken,
            'X-User-Id': authData.userId,
          },
        });

        if (!messagesResponse.ok) {
          throw new Error('Failed to fetch messages');
        }

        const { messages: chatMessages } = await messagesResponse.json();
        setMessages(chatMessages);
        setError(null);
      } catch (err) {
        console.error('Error fetching messages:', err);
        setError(err instanceof Error ? err.message : 'Failed to fetch messages');
      } finally {
        setLoading(false);
      }
    };

    fetchMessages();
  }, []);

  return (
    <Card className="transition-transform duration-500 ease-in-out transform hover:scale-105">
      <CardHeader>
        <CardTitle>Parole Messages</CardTitle>
      </CardHeader>
      <CardContent>
        {loading && <p>Loading messages...</p>}
        {error && <p className="text-red-500">Error: {error}</p>}
        {!loading && !error && (
          <div className="space-y-4">
            {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">{message.msg}</p>
                <p className="text-xs text-gray-500">
                  {new Date(message.ts).toLocaleString()}
                </p>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
} 