import { useChatStore } from '@/stores/chatStore';
import {
  differenceInHours,
  differenceInMinutes,
  format,
  isYesterday,
} from 'date-fns';
import { ChevronRight, User } from 'lucide-react';
import { useState, type FC } from 'react';
import { ScrollArea } from './ui/scroll-area';

type UsersSidebarProps = {
  roomId: string;
};

export const UsersSidebar: FC<UsersSidebarProps> = ({ roomId }) => {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const { chatRooms, onlineUsers } = useChatStore();

  const currentRoom = chatRooms.find((room) => room.id === roomId);

  const formatLastSeen = (lastSeen: string) => {
    if (!lastSeen) return 'Unknown';

    const date = new Date(lastSeen);
    const now = new Date();

    const mins = differenceInMinutes(now, date);
    const hours = differenceInHours(now, date);

    if (mins < 1) return 'just now';
    if (mins < 60) return `${mins}m ago`;
    if (hours < 24) return `${hours}h ago`;
    if (isYesterday(date)) return 'yesterday';

    return format(date, 'MMM d, yyyy');
  };

  const onlineMembers =
    currentRoom?.members.filter((member) => onlineUsers.has(member.userId)) ??
    [];

  const offlineMembers =
    currentRoom?.members.filter((member) => !onlineUsers.has(member.userId)) ??
    [];

  if (!currentRoom) return null;

  return (
    <div
      className={`border-l border-gray-200 bg-gray-50 dark:bg-gray-800 dark:border-gray-700 transition-all duration-300 flex ${
        isCollapsed ? 'w-12' : 'w-64'
      }`}
    >
      <button
        onClick={() => setIsCollapsed(!isCollapsed)}
        className="h-12 w-12 flex items-center justify-center text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
      >
        <ChevronRight
          className={`h-5 w-5 transition-transform ${isCollapsed ? 'rotate-180' : ''}`}
        />
      </button>

      {!isCollapsed && (
        <div className="flex-1 flex flex-col">
          <div className="p-4 border-b border-gray-200 dark:border-gray-700">
            <h3 className="font-medium text-sm dark:text-white">
              Users in {currentRoom.name}
            </h3>
          </div>

          <ScrollArea className="flex-1">
            <div className="p-3">
              {onlineMembers.length > 0 && (
                <div className="mb-6">
                  <h4 className="text-xs font-semibold text-gray-500 dark:text-gray-400 mb-2 uppercase tracking-wider">
                    Online • {onlineMembers.length}
                  </h4>
                  <div className="space-y-3">
                    {onlineMembers.map((member) => (
                      <div key={member.id} className="flex items-center gap-3">
                        <div className="relative">
                          <div className="w-10 h-10 rounded-full bg-blue-500 text-white flex items-center justify-center">
                            {member.user.avatar ? (
                              <img
                                src={member.user.avatar}
                                alt={member.user.username}
                                className="w-full h-full rounded-full"
                              />
                            ) : (
                              <User className="h-5 w-5" />
                            )}
                          </div>
                          <div className="absolute bottom-0 right-0 w-3 h-3 bg-green-500 border-2 border-white dark:border-gray-800 rounded-full"></div>
                        </div>
                        <div className="flex flex-col">
                          <div className="flex items-center gap-2">
                            <p className="text-sm font-medium dark:text-white">
                              {member.user.username}
                            </p>
                            {member.role && (
                              <span className="px-1.5 py-0.5 text-xs rounded-full bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 font-medium">
                                {member.role}
                              </span>
                            )}
                          </div>
                          <div className="flex items-center gap-1.5 mt-0.5">
                            <div className="w-1.5 h-1.5 rounded-full bg-green-500"></div>
                            <p className="text-xs text-gray-500 dark:text-gray-400">
                              Online now
                            </p>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {offlineMembers.length > 0 && (
                <div>
                  <h4 className="text-xs font-semibold text-gray-500 dark:text-gray-400 mb-2 uppercase tracking-wider">
                    Offline • {offlineMembers.length}
                  </h4>
                  <div className="space-y-3">
                    {offlineMembers.map((member) => (
                      <div key={member.id} className="flex items-center gap-3">
                        <div className="relative">
                          <div className="w-10 h-10 rounded-full bg-gray-300 dark:bg-gray-600 text-gray-600 dark:text-gray-300 flex items-center justify-center">
                            {member.user.avatar ? (
                              <img
                                src={member.user.avatar}
                                alt={member.user.username}
                                className="w-full h-full rounded-full opacity-70"
                              />
                            ) : (
                              <User className="h-5 w-5" />
                            )}
                          </div>
                          <div className="absolute bottom-0 right-0 w-3 h-3 bg-gray-400 border-2 border-white dark:border-gray-800 rounded-full"></div>
                        </div>
                        <div>
                          <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
                            {member.user.username}
                          </p>
                          <p className="text-xs text-gray-500 dark:text-gray-400">
                            Last seen {formatLastSeen(member.user.lastSeen)}
                          </p>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </ScrollArea>
        </div>
      )}
    </div>
  );
};
