import React, { useState, useEffect } from 'react';
import { apiFetch } from '@/utils/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Loader2, Hash, Users, MessageSquare, MessageCircle, Users2 } from 'lucide-react';
import config from '@/config';

interface Room {
  id: number;
  name: string;
  fname: string;
  type: string;
  msgs: number;
  last_message_date: string;
  display_name: string;
  userscount?: number;
  description?: string;
  teamid?: string;
  archived?: boolean;
  open?: boolean;
  participants?: {
    username: string;
    name: string;
    mongo_id: string;
    avataretag?: string;
  }[];
}

interface RoomListProps {
  selectedUserId: string;
  selectedRoomId: string | null;
  onRoomSelect: (roomId: string) => void;
}

export function RoomList({ selectedUserId, selectedRoomId, onRoomSelect }: RoomListProps) {
  const [rooms, setRooms] = useState<Room[]>([]);
  const [filteredRooms, setFilteredRooms] = useState<Room[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [searchFilter] = useState('');

  useEffect(() => {
    if (!selectedUserId) {
      setRooms([]);
      setFilteredRooms([]);
      return;
    }

    const fetchUserRooms = async () => {
      setLoading(true);
      setError(null);
      
      try {
        const response = await apiFetch(`${config.chatUrl}/users/${selectedUserId}/rooms`);
        const data = await response.json();
        
        if (data.status === 'success') {
          setRooms(data.rooms);
          setFilteredRooms(data.rooms);
        } else {
          throw new Error(data.error || 'Failed to fetch rooms');
        }
      } catch (err) {
        console.error('Error fetching user rooms:', err);
        setError(err instanceof Error ? err.message : 'An error occurred');
      } finally {
        setLoading(false);
      }
    };

    fetchUserRooms();
  }, [selectedUserId]);

  useEffect(() => {
    if (!searchFilter) {
      setFilteredRooms(rooms);
    } else {
      const filtered = rooms.filter(room => 
        (room.display_name?.toLowerCase() || '').includes(searchFilter.toLowerCase()) ||
        (room.name?.toLowerCase() || '').includes(searchFilter.toLowerCase()) ||
        (room.fname?.toLowerCase() || '').includes(searchFilter.toLowerCase())
      );
      setFilteredRooms(filtered);
    }
  }, [searchFilter, rooms]);

  const groupRoomsByType = (rooms: Room[]) => {
    const teams: Room[] = [];
    const discussions: Room[] = [];
    const channels: Room[] = [];
    const directMessages: Room[] = [];

    rooms.forEach(room => {
      switch (room.type) {
        case 'p':
          if (room.teamid) {
            teams.push(room);
          } else {
            discussions.push(room);
          }
          break;
        case 'c':
          channels.push(room);
          break;
        case 'd':
          directMessages.push(room);
          break;
        default:
          channels.push(room); // fallback for unknown types
      }
    });

    // Sort each group by message count descending
    const sortByMessages = (a: Room, b: Room) => (b.msgs || 0) - (a.msgs || 0);
    
    teams.sort(sortByMessages);
    discussions.sort(sortByMessages);
    channels.sort(sortByMessages);
    directMessages.sort(sortByMessages);

    return { teams, discussions, channels, directMessages };
  };

  const renderRoomIcon = (room: Room) => {
    // For direct messages, show participant avatars
    if (room.type === 'd' && room.participants && room.participants.length > 0) {
      if (room.participants.length === 1) {
        // Single participant - show their avatar
        const participant = room.participants[0];
        return (
          <Avatar className="h-10 w-10">
            <AvatarImage 
              src={`${config.chatUrl}/avatar/${participant.mongo_id}`}
              alt={participant.name || participant.username}
            />
            <AvatarFallback className="text-lg">
              {(participant.name || participant.username).charAt(0).toUpperCase()}
            </AvatarFallback>
          </Avatar>
        );
      } else {
        // Multiple participants - show overlapping avatars
        return (
          <div className="relative flex items-center h-10 w-10">
            {room.participants.slice(0, 3).map((participant, index) => (  
              <Avatar 
                key={participant.mongo_id} 
                className={`h-8 w-8 border-2 border-white ${index > 0 ? '-ml-4' : ''}`}
                style={{ zIndex: 30 - index }}
              >
                <AvatarImage 
                  src={`${config.chatUrl}/avatar/${participant.mongo_id}`}
                  alt={participant.name || participant.username}
                />
                <AvatarFallback className="text-lg">
                  {(participant.name || participant.username).charAt(0).toUpperCase()}
                </AvatarFallback>
              </Avatar>
            ))}
          </div>
        );
      }
    }

    // For other room types, use icons
    switch (room.type) {
      case 'c':
        return (
          <div className="h-10 w-10 bg-blue-50 rounded-full flex items-center justify-center">
            <Hash className="h-6 w-6 text-blue-500" />
          </div>
        );
      case 'p':
        // Distinguish between teams and discussions based on teamid
        if (room.teamid) {
          return (
            <div className="h-10 w-10 bg-purple-50 rounded-full flex items-center justify-center">
              <Users2 className="h-6 w-6 text-purple-500" />
            </div>
          ); // Teams
        } else {
          return (
            <div className="h-10 w-10 bg-orange-50 rounded-full flex items-center justify-center">
              <MessageCircle className="h-6 w-6 text-orange-500" />
            </div>
          ); // Discussions
        }
      case 'd':
        return (
          <div className="h-12 w-12 bg-green-50 rounded-full flex items-center justify-center">
            <MessageSquare className="h-6 w-6 text-green-500" />
          </div>
        );
      default:
        return (
          <div className="h-12 w-12 bg-gray-50 rounded-full flex items-center justify-center">
            <Users className="h-6 w-6 text-gray-500" />
          </div>
        );
    }
  };

  if (!selectedUserId) {
    return (
      <Card className="h-full">
        <CardHeader>
          <CardTitle>Rooms</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground text-sm">
            Select a user from the dropdown above to view their rooms.
          </p>
        </CardContent>
      </Card>
    );
  }

  if (loading) {
    return (
      <Card className="h-full">
        <CardHeader>
          <CardTitle>Loading Rooms...</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center gap-2">
            <Loader2 className="h-4 w-4 animate-spin" />
            <span className="text-sm">Fetching rooms for selected user...</span>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card className="h-full border-red-200 bg-red-50">
        <CardHeader>
          <CardTitle className="text-red-800">Error Loading Rooms</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-red-700 text-sm">{error}</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="h-full flex flex-col">
      <CardHeader className="pb-3">
        <CardTitle className="text-lg">Rooms</CardTitle>
      </CardHeader>
      
      <CardContent className="flex-1 p-0 overflow-hidden">
        <div className="h-full overflow-y-auto">
          {filteredRooms.length === 0 ? (
            <div className="p-4">
              <p className="text-muted-foreground text-sm">
                {searchFilter ? 'No rooms match your search.' : 'No rooms found for this user.'}
              </p>
            </div>
          ) : (
            <div className="space-y-3 px-2 pb-4">
              {(() => {
                const { teams, discussions, channels, directMessages } = groupRoomsByType(filteredRooms);
                
                const renderRoomGroup = (title: string, rooms: Room[], icon: React.ReactNode) => {
                  if (rooms.length === 0) return null;
                  
                  return (
                    <div key={title} className="space-y-0.5">
                      <div className="flex items-center gap-2 px-2 py-1 border-b border-gray-100">
                        {icon}
                        <h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                          {title} ({rooms.length})
                        </h3>
                      </div>
                      <div className="space-y-0.5">
                        {rooms.map((room) => (
                          <div
                            key={room.id}
                            onClick={() => onRoomSelect(room.id.toString())}
                            className={`
                              flex items-center justify-between py-0.5 px-3 rounded-lg cursor-pointer transition-colors
                              hover:bg-gray-100 
                              ${selectedRoomId === room.id.toString() ? 'bg-blue-50 border-l-4 border-blue-500' : ''}
                              ${(room.open === false || room.archived === true) ? 'opacity-60' : ''}
                            `}
                          >
                                                        <div className="grid grid-cols-4 items-center gap-2 min-w-0 flex-1">
                              {renderRoomIcon(room)}
                              <div className="min-w-0 flex-1 col-span-3">
                                <div className="flex items-center justify-between">
                                  <div className={`font-medium text-sm truncate ${(room.open === false || room.archived === true) ? 'text-muted-foreground' : ''}`}>
                                    {room.display_name || room.fname || room.name || 'Unnamed Room'}
                                  </div>
                                  {room.msgs > 0 && (
                                    <span className="text-xs text-muted-foreground ml-2 flex-shrink-0">
                                      {room.msgs} msgs
                                    </span>
                                  )}
                                </div>
                                {room.description && (
                                  <div className="text-xs text-muted-foreground truncate">
                                    {room.description}
                                  </div>
                                )}
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  );
                };

                return (
                  <>
                    {renderRoomGroup('Teams', teams, <Users2 className="h-3 w-3 text-purple-500" />)}
                    {renderRoomGroup('Discussions', discussions, <MessageCircle className="h-3 w-3 text-orange-500" />)}
                    {renderRoomGroup('Channels', channels, <Hash className="h-3 w-3 text-blue-500" />)}
                    {renderRoomGroup('Direct Messages', directMessages, <MessageSquare className="h-3 w-3 text-green-500" />)}
                  </>
                );
              })()}
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  );
} 
