import { useState, useEffect } from 'react';
import { apiFetch } from '@/utils/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Loader2, Hash, Lock, Users, MessageSquare } from 'lucide-react';
import config from '@/config';

interface Room {
  id: number;
  name: string;
  fname: string;
  type: string;
  msgs: number;
  last_message_date: string;
}

interface ChatTestProps {
  selectedUserId: string;
}

export function ChatTest({ selectedUserId }: ChatTestProps) {
  const [rooms, setRooms] = useState<Room[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!selectedUserId) {
      setRooms([]);
      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);
        } 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]);

  const getRoomIcon = (roomType: string) => {
    switch (roomType) {
      case 'c':
        return <Hash className="h-4 w-4 text-blue-500" />;
      case 'p':
        return <Lock className="h-4 w-4 text-orange-500" />;
      case 'd':
        return <MessageSquare className="h-4 w-4 text-green-500" />;
      default:
        return <Users className="h-4 w-4 text-gray-500" />;
    }
  };

  const getRoomTypeLabel = (roomType: string) => {
    switch (roomType) {
      case 'c':
        return 'Channel';
      case 'p':
        return 'Private';
      case 'd':
        return 'Direct';
      default:
        return 'Unknown';
    }
  };

  if (!selectedUserId) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Database Connection Test</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground">
            Select a user from the dropdown above to view their rooms and test the database connection.
          </p>
        </CardContent>
      </Card>
    );
  }

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

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

  return (
    <Card>
      <CardHeader>
        <CardTitle>User Rooms ({rooms.length})</CardTitle>
        <p className="text-sm text-muted-foreground">
          Rooms accessible to the selected user
        </p>
      </CardHeader>
      <CardContent>
        {rooms.length === 0 ? (
          <p className="text-muted-foreground">No rooms found for this user.</p>
        ) : (
          <div className="space-y-2">
            {rooms.map((room) => (
              <div
                key={room.id}
                className="flex items-center justify-between p-3 border rounded-lg hover:bg-gray-50"
              >
                <div className="flex items-center gap-3">
                  {getRoomIcon(room.type)}
                  <div>
                    <div className="font-medium">
                      {room.fname || room.name || 'Unnamed Room'}
                    </div>
                    <div className="text-sm text-muted-foreground">
                      {room.name && room.fname !== room.name && (
                        <span className="font-mono">#{room.name}</span>
                      )}
                    </div>
                  </div>
                </div>
                
                <div className="flex items-center gap-2">
                  <Badge variant="secondary">
                    {getRoomTypeLabel(room.type)}
                  </Badge>
                  <Badge variant="outline">
                    {room.msgs} messages
                  </Badge>
                  {room.last_message_date && (
                    <Badge variant="outline" className="text-xs">
                      {new Date(room.last_message_date).toLocaleDateString()}
                    </Badge>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
} 
