import { chatAPI } from '@/lib/api';
import { useAuthStore } from '@/stores/authStore';
import { useChatStore } from '@/stores/chatStore';
import { useSocketStore } from '@/stores/socketStore';
import type { ChatRoom, CreateChatRoomRequest } from '@/types';
import { useQuery } from '@tanstack/react-query';
import {
  Laptop,
  LogOut,
  MessageCircle,
  Moon,
  Plus,
  Settings,
  Sun,
  User,
  Users,
} from 'lucide-react';
import { useTheme } from 'next-themes';
import { useState, type FC, type FormEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import { UserSettingsDialog } from './SettingsDialog';
import { Badge } from './ui/badge';
import { Button } from './ui/button';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from './ui/dialog';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Popover, PopoverContent, PopoverTrigger } from './ui/popover';
import { ScrollArea } from './ui/scroll-area';
import { Textarea } from './ui/textarea';

type ChatSidebarProps = {
  selectedRoomId: string | null;
  onRoomSelect: (roomId: string) => void;
};

export const ChatSidebar: FC<ChatSidebarProps> = ({
  selectedRoomId,
  onRoomSelect,
}) => {
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [isUserMenuOpen, setIsUserMenuOpen] = useState(false);
  const [isSettingsDialogOpen, setIsSettingsDialogOpen] = useState(false);
  const [newRoomData, setNewRoomData] = useState<CreateChatRoomRequest>({
    name: '',
    description: '',
    memberUsernames: [],
  });

  const { chatRooms, onlineUsers, setChatRooms } = useChatStore();
  const { user, logout } = useAuthStore();
  const { socket } = useSocketStore();
  const navigate = useNavigate();
  const { theme, setTheme } = useTheme();

  const { isLoading } = useQuery({
    queryKey: ['chatRooms'],
    queryFn: async () => {
      const response = await chatAPI.getChatRooms();
      if (response.data.success) {
        setChatRooms(response.data.data);
        return response.data.data;
      }
      throw new Error(response.data.error ?? 'Failed to fetch chat rooms');
    },
  });

  const handleCreateRoom = (e: FormEvent) => {
    e.preventDefault();

    if (!socket) {
      toast.error('Socket connection is not established');
      return;
    }

    socket.emit('create_chat_room', newRoomData);

    setNewRoomData({ name: '', description: '', memberUsernames: [] });
    setIsCreateDialogOpen(false);
  };

  const getOnlineMembersCount = (room: ChatRoom) => {
    return room.members.filter((member) => onlineUsers.has(member.userId))
      .length;
  };

  const handleRoomSelect = (roomId: string) => {
    onRoomSelect(roomId);
    navigate(`/room/${roomId}`);
  };

  const handleLogout = () => {
    logout();
    navigate('/login');
    setIsUserMenuOpen(false);
  };

  const handleThemeChange = (newTheme: string) => {
    setTheme(newTheme);
    setIsUserMenuOpen(false);
  };

  if (isLoading) {
    return (
      <div className="w-80 bg-gray-50 border-r border-gray-200 p-4">
        <div className="animate-pulse space-y-4">
          <div className="h-4 bg-gray-200 rounded w-3/4"></div>
          <div className="h-4 bg-gray-200 rounded w-3/4"></div>
          <div className="h-4 bg-gray-200 rounded w-3/4"></div>
        </div>
      </div>
    );
  }

  return (
    <div className="w-80 bg-gray-50 border-r border-gray-200 flex flex-col dark:bg-gray-800 dark:border-gray-700">
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold dark:text-white">Chat Rooms</h2>
          <Dialog
            open={isCreateDialogOpen}
            onOpenChange={setIsCreateDialogOpen}
          >
            <DialogTrigger asChild>
              <Button size="sm" variant="outline">
                <Plus className="h-4 w-4" />
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Create New Chat Room</DialogTitle>
              </DialogHeader>
              <form onSubmit={handleCreateRoom} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="room-name">Room Name</Label>
                  <Input
                    id="room-name"
                    value={newRoomData.name}
                    onChange={(e) =>
                      setNewRoomData({ ...newRoomData, name: e.target.value })
                    }
                    required
                    placeholder="Enter room name"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="room-description">
                    Description (optional)
                  </Label>
                  <Textarea
                    id="room-description"
                    value={newRoomData.description}
                    onChange={(e) =>
                      setNewRoomData({
                        ...newRoomData,
                        description: e.target.value,
                      })
                    }
                    placeholder="Enter room description"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="member-usernames">
                    Member Usernames (comma-separated)
                  </Label>
                  <Input
                    id="member-usernames"
                    value={newRoomData.memberUsernames.join(', ')}
                    onChange={(e) =>
                      setNewRoomData({
                        ...newRoomData,
                        memberUsernames: e.target.value
                          .split(',')
                          .map((u) => u.trim())
                          .filter((u) => u.length > 0),
                      })
                    }
                    placeholder="user1, user2, user3"
                  />
                </div>
                <Button type="submit" className="w-full">
                  Create Room
                </Button>
              </form>
            </DialogContent>
          </Dialog>
        </div>
      </div>
      <ScrollArea className="flex-1">
        <div className="p-2 space-y-2">
          {chatRooms.map((room: ChatRoom) => (
            <div
              key={room.id}
              className={`p-3 rounded-lg cursor-pointer transition-colors ${
                selectedRoomId === room.id
                  ? 'bg-blue-100 border-blue-200 border dark:bg-blue-900/30 dark:border-blue-800'
                  : 'bg-white hover:bg-gray-100 border border-gray-200 dark:bg-gray-700 dark:border-gray-600 dark:hover:bg-gray-600'
              }`}
              onClick={() => handleRoomSelect(room.id)}
            >
              <div className="flex items-center justify-between mb-1">
                <h3 className="font-medium text-sm dark:text-white">
                  {room.name}
                </h3>
                <div className="flex items-center space-x-1">
                  <Badge variant="secondary" className="text-xs">
                    <Users className="h-3 w-3 mr-1" />
                    {getOnlineMembersCount(room)} / {room.members.length} online
                  </Badge>
                </div>
              </div>
              {room.description && (
                <p className="text-xs text-gray-500 mb-2 truncate dark:text-gray-300">
                  {room.description}
                </p>
              )}
              <div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
                <div className="flex items-center">
                  <MessageCircle className="h-3 w-3 mr-1" />
                  {room._count.messages} messages
                </div>
                <div className="flex -space-x-1">
                  {room.members.slice(0, 3).map((member) => (
                    <div
                      key={member.id}
                      className="relative w-4 h-4"
                      title={`${member.user.username} - ${
                        onlineUsers.has(member.userId) ? 'Online' : 'Offline'
                      }`}
                    >
                      <div className="w-4 h-4 rounded-full border border-white dark:border-gray-800 flex items-center justify-center text-xs font-medium bg-gray-300 dark:bg-gray-600 overflow-hidden">
                        {member.user.avatar ? (
                          <img
                            src={member.user.avatar}
                            alt={member.user.username}
                            className="w-full h-full object-cover"
                          />
                        ) : (
                          member.user.username.charAt(0).toUpperCase()
                        )}
                      </div>
                      {onlineUsers.has(member.userId) && (
                        <div className="absolute bottom-0 right-0 w-1.5 h-1.5 bg-green-500 border border-white dark:border-gray-800 rounded-full z-10"></div>
                      )}
                    </div>
                  ))}
                  {room.members.length > 3 && (
                    <div className="w-4 h-4 rounded-full border border-white dark:border-gray-800 bg-gray-200 dark:bg-gray-600 flex items-center justify-center text-xs">
                      +{room.members.length - 3}
                    </div>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      </ScrollArea>
      <div className="p-4 border-t border-gray-200 mt-auto dark:border-gray-700">
        <Popover open={isUserMenuOpen} onOpenChange={setIsUserMenuOpen}>
          <PopoverTrigger asChild>
            <div className="flex items-center space-x-3 cursor-pointer p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
              <div className="relative">
                <div className="w-10 h-10 rounded-full bg-blue-500 text-white flex items-center justify-center">
                  {user?.avatar ? (
                    <img
                      src={user.avatar}
                      alt={user?.username}
                      className="w-full h-full rounded-full"
                    />
                  ) : (
                    <User className="h-6 w-6" />
                  )}
                </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-1">
                <p className="font-medium text-sm dark:text-white">
                  {user?.username}
                </p>
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  Online
                </p>
              </div>
            </div>
          </PopoverTrigger>
          <PopoverContent
            className="w-48 p-0 dark:bg-gray-800 dark:border-gray-700"
            align="start"
            side="top"
          >
            <div className="py-1">
              <div className="border-b border-gray-200 dark:border-gray-700 pb-1">
                <button
                  className="w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white flex items-center gap-2"
                  onClick={() => handleThemeChange('light')}
                >
                  <Sun className="h-4 w-4" />
                  Light
                  {theme === 'light' && (
                    <span className="ml-auto text-blue-500">✓</span>
                  )}
                </button>
                <button
                  className="w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white flex items-center gap-2"
                  onClick={() => handleThemeChange('dark')}
                >
                  <Moon className="h-4 w-4" />
                  Dark
                  {theme === 'dark' && (
                    <span className="ml-auto text-blue-500">✓</span>
                  )}
                </button>
                <button
                  className="w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white flex items-center gap-2"
                  onClick={() => handleThemeChange('system')}
                >
                  <Laptop className="h-4 w-4" />
                  System
                  {theme === 'system' && (
                    <span className="ml-auto text-blue-500">✓</span>
                  )}
                </button>
              </div>
              <button
                className="w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white flex items-center gap-2"
                onClick={() => {
                  setIsUserMenuOpen(false);
                  setIsSettingsDialogOpen(true);
                }}
              >
                <Settings className="h-4 w-4" />
                Settings
              </button>
              <button
                className="w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700 text-red-500 flex items-center gap-2"
                onClick={handleLogout}
              >
                <LogOut className="h-4 w-4" />
                Logout
              </button>
            </div>
          </PopoverContent>
        </Popover>
      </div>
      <UserSettingsDialog
        open={isSettingsDialogOpen}
        onOpenChange={setIsSettingsDialogOpen}
      />
    </div>
  );
};
