"use client";

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

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 router = useRouter();
  const { data: session, status } = useSession();

  const fetchMessages = async (isRefresh = false) => {
    try {
      if (isRefresh) {
        setRefreshing(true);
      }

      const response = await fetch('/api/rocket-chat/messages', {
        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);
      const errorMessage = err instanceof Error ? err.message : 'Failed to fetch messages';
      setError(errorMessage);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

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

  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 h-full 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
        </CardTitle>
        <Button 
          variant="ghost" 
          size="icon"
          onClick={(e) => {
            e.stopPropagation();
            fetchMessages(true);
          }}
          disabled={refreshing}
          className={`${refreshing ? 'animate-spin' : ''} text-gray-600 hover:text-gray-900`}
        >
          <RefreshCw className="h-4 w-4" />
        </Button>
      </CardHeader>
      <CardContent className="p-4">
        {loading && <p className="text-center text-gray-500">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-4 max-h-[300px] overflow-y-auto">
            {messages.length === 0 ? (
              <p className="text-center text-gray-500">No messages found</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>
  );
} 