import React, { useState, useEffect, useContext } from 'react';
import { apiFetch } from '@/utils/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Loader2, Search } from 'lucide-react';
import { RoomList } from '@/components/chat/RoomList';
import { ChatRoom } from '@/components/chat/ChatRoom';
import { SearchResults } from '@/components/chat/SearchResults';
import { AuthContext } from '@/contexts/AuthContext';
import config from '@/config';

interface User {
  id: number;
  username: string;
  name: string;
  type: string;
  active: boolean;
  status?: string;
  lastlogin?: string;
  statustext?: string;
  statusconnection?: string;
  mongo_id?: string;
  avataretag?: string;
}

interface SearchResult {
  id: number;
  msg: string;
  ts: string;
  u: {
    username: string;
    name?: string;
  };
  room_id: number;
  room_name: string;
  room_fname: string;
  room_type: string;
}

export function Chat() {
  const { user: currentUser } = useContext(AuthContext);
  const [users, setUsers] = useState<User[]>([]);
  const [selectedUserId, setSelectedUserId] = useState<string>('');
  const [selectedRoomId, setSelectedRoomId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [userRocketChatId, setUserRocketChatId] = useState<string | null>(null);
  
  // Global search state
  const [globalSearchQuery, setGlobalSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<SearchResult[]>([]);
  const [showSearchResults, setShowSearchResults] = useState(false);
  const [searching, setSearching] = useState(false);

  useEffect(() => {
    if (currentUser) {
      setUserRocketChatId(currentUser.rocket_chat_user_id || null);
    }
  }, [currentUser]);

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const response = await apiFetch(`${config.chatUrl}/users`);
        const data = await response.json();
        
        if (data.status === 'success') {
          setUsers(data.users);
          
          // Auto-select user based on permissions
          if (currentUser && !currentUser.is_admin && userRocketChatId) {
            console.log('Attempting to auto-select user:', {
              currentUser: currentUser.username,
              userRocketChatId,
              userRocketChatIdType: typeof userRocketChatId,
              availableUsers: data.users.map((u: User) => ({ id: u.id, idType: typeof u.id }))
            });
            
            // Non-admin users should only see their connected rocket chat user
            const userRocketChatUser = data.users.find((user: User) => user.id.toString() === userRocketChatId?.toString());
            console.log('Found matching user:', userRocketChatUser);
            
            if (userRocketChatUser) {
              setSelectedUserId(userRocketChatUser.id.toString());
              console.log('Auto-selected user ID:', userRocketChatUser.id.toString());
            }
          }
        } else {
          throw new Error(data.error || 'Failed to fetch users');
        }
      } catch (err) {
        console.error('Error fetching users:', err);
        setError(err instanceof Error ? err.message : 'An error occurred');
      } finally {
        setLoading(false);
      }
    };

    if (currentUser) {
      fetchUsers();
    }
  }, [currentUser, userRocketChatId]);

  const handleUserChange = (userId: string) => {
    // Only allow admins to change users, or if the user is selecting their own connected account
    if (currentUser?.is_admin || userId === userRocketChatId) {
      setSelectedUserId(userId);
      setSelectedRoomId(null); // Reset room selection when user changes
      setGlobalSearchQuery(''); // Clear search when user changes
      setShowSearchResults(false);
    }
  };

  const handleRoomSelect = (roomId: string) => {
    setSelectedRoomId(roomId);
    setShowSearchResults(false); // Close search results when room is selected
  };

  const handleGlobalSearch = async () => {
    if (!globalSearchQuery || globalSearchQuery.length < 2 || !selectedUserId) return;
    
    setSearching(true);
    try {
      const response = await apiFetch(
        `${config.chatUrl}/users/${selectedUserId}/search?q=${encodeURIComponent(globalSearchQuery)}&limit=20`
      );
      const data = await response.json();
      
      if (data.status === 'success') {
        setSearchResults(data.results);
        setShowSearchResults(true);
      }
    } catch (err) {
      console.error('Error searching messages:', err);
    } finally {
      setSearching(false);
    }
  };

  const handleSearchKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleGlobalSearch();
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-6">
        <Card className="border-red-200 bg-red-50">
          <CardHeader>
            <CardTitle className="text-red-800">Connection Error</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-red-700">{error}</p>
            <p className="text-sm text-red-600 mt-2">
              Make sure the chat server is running and the database is accessible.
            </p>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold">Chat</h1>
        
        <div className="flex items-center gap-4">
          {/* Global Search */}
          {selectedUserId && (
            <div className="relative">
              <div className="flex gap-2">
                <Input
                  placeholder="Search all messages..."
                  value={globalSearchQuery}
                  onChange={(e) => setGlobalSearchQuery(e.target.value)}
                  onKeyPress={handleSearchKeyPress}
                  className="w-64"
                />
                <Button 
                  onClick={handleGlobalSearch} 
                  disabled={searching || globalSearchQuery.length < 2}
                  size="icon"
                  variant="outline"
                >
                  {searching ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  ) : (
                    <Search className="h-4 w-4" />
                  )}
                </Button>
              </div>
              
              {showSearchResults && (
                <SearchResults
                  results={searchResults}
                  query={globalSearchQuery}
                  onClose={() => setShowSearchResults(false)}
                  onRoomSelect={handleRoomSelect}
                />
              )}
            </div>
          )}
          
{currentUser?.is_admin ? (
            <Select value={selectedUserId} onValueChange={handleUserChange}>
              <SelectTrigger className="w-64">
                <SelectValue placeholder="View as user..." />
              </SelectTrigger>
              <SelectContent>
                {users.map((user) => (
                  <SelectItem key={user.id} value={user.id.toString()}>
                    <div className="flex items-center gap-2">
                      <Avatar className="h-6 w-6">
                        <AvatarImage 
                          src={user.mongo_id ? `${config.chatUrl}/avatar/${user.mongo_id}` : undefined}
                          alt={user.name || user.username}
                        />
                        <AvatarFallback className="text-xs">
                          {(user.name || user.username).charAt(0).toUpperCase()}
                        </AvatarFallback>
                      </Avatar>
                      <span className={user.active ? '' : 'text-muted-foreground'}>
                        {user.name || user.username}
                        {!user.active && <span className="text-xs ml-1">(inactive)</span>}
                      </span>
                    </div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          ) : (
            <div className="flex items-center gap-2 p-2 border rounded-md bg-muted w-64">
              {selectedUserId && users.length > 0 ? (
                <>
                  {(() => {
                    const selectedUser = users.find(u => u.id.toString() === selectedUserId);
                    return selectedUser ? (
                      <>
                        <Avatar className="h-6 w-6">
                          <AvatarImage 
                            src={selectedUser.mongo_id ? `${config.chatUrl}/avatar/${selectedUser.mongo_id}` : undefined}
                            alt={selectedUser.name || selectedUser.username}
                          />
                          <AvatarFallback className="text-xs">
                            {(selectedUser.name || selectedUser.username).charAt(0).toUpperCase()}
                          </AvatarFallback>
                        </Avatar>
                        <span>
                          Viewing as: {selectedUser.name || selectedUser.username}
                        </span>
                      </>
                    ) : (
                      <span className="text-muted-foreground">No connected Rocket Chat user</span>
                    );
                  })()}
                </>
              ) : (
                <span className="text-muted-foreground">
                  {userRocketChatId ? 'Loading...' : 'No connected Rocket Chat user'}
                </span>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Chat Interface */}
      {selectedUserId ? (
        <div className="grid grid-cols-12 gap-6 h-[700px]">
          {/* Room List Sidebar */}
          <div className="col-span-4 h-[85vh] overflow-y-auto">
            <RoomList
              selectedUserId={selectedUserId}
              selectedRoomId={selectedRoomId}
              onRoomSelect={handleRoomSelect}
            />
          </div>
          
          {/* Chat Messages Area */}
          <div className="col-span-8 h-[85vh] overflow-y-auto">
            <ChatRoom
              roomId={selectedRoomId || ''}
              selectedUserId={selectedUserId}
            />
          </div>
        </div>
      ) : (
        <Card>
          <CardContent className="flex items-center justify-center h-64">
            {currentUser?.is_admin ? (
              <p className="text-muted-foreground">
                Select a user to view their chat rooms and messages.
              </p>
            ) : (
              <div className="text-center space-y-2">
                <p className="text-muted-foreground">
                  No Rocket Chat user connected to your account.
                </p>
                <p className="text-sm text-muted-foreground">
                  Please contact your administrator to connect your account with a Rocket Chat user.
                </p>
              </div>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  );
} 
