import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import { Button } from './ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/card';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Textarea } from './ui/textarea';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from './ui/dialog';
import { Badge } from './ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs';
import { ScrollArea } from './ui/scroll-area';
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar';
import { useToast } from '../hooks/use-toast';
import { 
  MessageCircle, 
  UserPlus, 
  Users, 
  Send, 
  Bell, 
  BellDot,
  MessageSquare,
  User,
  Clock,
  Check,
  X,
  Settings,
  Eye,
  EyeOff,
  Circle,
  Minimize2,
  Maximize2
} from 'lucide-react';

const BACKEND_URL = process.env.REACT_APP_BACKEND_URL;
const API = `${BACKEND_URL}/api`;

// WebSocket connection for real-time messaging
let socket = null;

// Clickable Username Component
export const ClickableUsername = ({ userId, username, className = "", onClick }) => {
  const handleClick = () => {
    if (onClick) {
      onClick(userId, username);
    } else {
      // Default behavior - navigate to user profile
      window.location.href = `/profile/${userId}`;
    }
  };

  return (
    <span 
      className={`cursor-pointer hover:text-blue-400 transition-colors ${className}`}
      onClick={handleClick}
      title={`View ${username}'s profile`}
    >
      {username}
    </span>
  );
};

// Friend Request Button Component
export const FriendRequestButton = ({ userId, currentFriendship, onUpdate }) => {
  const [isLoading, setIsLoading] = useState(false);
  const [showMessageDialog, setShowMessageDialog] = useState(false);
  const [message, setMessage] = useState('');
  const { toast } = useToast();

  const sendFriendRequest = async () => {
    setIsLoading(true);
    try {
      await axios.post(`${API}/social/friend-request`, {
        receiver_id: userId,
        message: message.trim() || undefined
      }, { withCredentials: true });

      toast({
        title: "Friend Request Sent",
        description: "Your friend request has been sent successfully.",
      });

      setShowMessageDialog(false);
      setMessage('');
      if (onUpdate) onUpdate();
    } catch (error) {
      toast({
        title: "Error",
        description: error.response?.data?.detail || "Failed to send friend request",
        variant: "destructive",
      });
    } finally {
      setIsLoading(false);
    }
  };

  if (currentFriendship === 'friends') {
    return (
      <Badge className="bg-green-600 text-white">
        <Users className="w-3 h-3 mr-1" />
        Friends
      </Badge>
    );
  }

  if (currentFriendship === 'pending') {
    return (
      <Badge className="bg-yellow-600 text-white">
        <Clock className="w-3 h-3 mr-1" />
        Request Pending
      </Badge>
    );
  }

  return (
    <>
      <Button
        variant="outline"
        size="sm"
        onClick={() => setShowMessageDialog(true)}
        disabled={isLoading}
        className="border-white/30 text-white hover:bg-white/10"
      >
        <UserPlus className="w-4 h-4 mr-2" />
        Add Friend
      </Button>

      <Dialog open={showMessageDialog} onOpenChange={setShowMessageDialog}>
        <DialogContent className="bg-black border-white/20 text-white">
          <DialogHeader>
            <DialogTitle>Send Friend Request</DialogTitle>
            <DialogDescription className="text-gray-400">
              Add a personal message (optional)
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4">
            <Textarea
              placeholder="Hi! I'd like to connect with you on Queens Mountain."
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              className="bg-white/10 border-white/20 text-white"
              maxLength={200}
            />
            <div className="text-xs text-gray-400">
              {message.length}/200 characters
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setShowMessageDialog(false)}
              className="border-white/30 text-white hover:bg-white/10"
            >
              Cancel
            </Button>
            <Button
              onClick={sendFriendRequest}
              disabled={isLoading}
              className="bg-blue-600 hover:bg-blue-700 text-white"
            >
              {isLoading ? 'Sending...' : 'Send Request'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
};

// Notification Bell Component - Fixed positioning for header
export const NotificationBell = ({ className = "" }) => {
  const [notifications, setNotifications] = useState([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [showDropdown, setShowDropdown] = useState(false);
  const [loading, setLoading] = useState(false);
  const dropdownRef = useRef(null);
  const { toast } = useToast();

  useEffect(() => {
    fetchNotifications();
    
    // Close dropdown when clicking outside
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setShowDropdown(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const fetchNotifications = async () => {
    setLoading(true);
    try {
      const response = await axios.get(`${API}/social/notifications`, {
        withCredentials: true
      });
      setNotifications(response.data.notifications || []);
      setUnreadCount(response.data.unread_count || 0);
    } catch (error) {
      console.error('Error fetching notifications:', error);
      // Use mock data for development
      setNotifications([
        {
          id: 1,
          type: 'message',
          title: 'New message from Sarah',
          content: 'Hey! I loved your latest story!',
          created_at: new Date().toISOString(),
          read: false
        },
        {
          id: 2,
          type: 'friend_request',
          title: 'New friend request',
          content: 'John Writer wants to be your friend',
          created_at: new Date().toISOString(),
          read: false
        },
        {
          id: 3,
          type: 'story_update',
          title: 'Story published',
          content: 'Your story "Epic Adventure" was published successfully',
          created_at: new Date().toISOString(),
          read: true
        }
      ]);
      setUnreadCount(2);
    } finally {
      setLoading(false);
    }
  };

  const markAsRead = async (notificationId) => {
    try {
      await axios.post(`${API}/social/notifications/${notificationId}/read`, {}, {
        withCredentials: true
      });
      
      setNotifications(prev => 
        prev.map(notif => 
          notif.id === notificationId 
            ? { ...notif, read: true }
            : notif
        )
      );
      
      setUnreadCount(prev => Math.max(0, prev - 1));
    } catch (error) {
      console.error('Error marking notification as read:', error);
    }
  };

  const markAllAsRead = async () => {
    try {
      await axios.post(`${API}/social/notifications/read-all`, {}, {
        withCredentials: true
      });
      
      setNotifications(prev => prev.map(notif => ({ ...notif, read: true })));
      setUnreadCount(0);
      
      toast({
        title: "All notifications marked as read",
        description: "Your notifications have been updated.",
      });
    } catch (error) {
      console.error('Error marking all as read:', error);
    }
  };

  return (
    <div className={`relative ${className}`} ref={dropdownRef}>
      <Button
        variant="ghost"
        size="sm"
        onClick={() => setShowDropdown(!showDropdown)}
        className="relative text-gray-300 hover:text-white hover:bg-white/10"
      >
        {unreadCount > 0 ? (
          <BellDot className="w-5 h-5" />
        ) : (
          <Bell className="w-5 h-5" />
        )}
        {unreadCount > 0 && (
          <Badge className="absolute -top-1 -right-1 bg-red-600 text-white text-xs min-w-[18px] h-[18px] rounded-full flex items-center justify-center p-0">
            {unreadCount > 99 ? '99+' : unreadCount}
          </Badge>
        )}
      </Button>

      {/* Dropdown - positioned to drop DOWN instead of up */}
      {showDropdown && (
        <div className="absolute top-full right-0 mt-2 w-80 bg-black border border-white/20 rounded-lg shadow-lg z-50">
          <div className="p-4 border-b border-white/20 flex items-center justify-between">
            <h3 className="text-white font-semibold">Notifications</h3>
            {unreadCount > 0 && (
              <Button
                variant="ghost"
                size="sm"
                onClick={markAllAsRead}
                className="text-blue-400 hover:text-blue-300 text-xs"
              >
                Mark all read
              </Button>
            )}
          </div>

          <ScrollArea className="max-h-80">
            {loading ? (
              <div className="p-6 text-center">
                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-white mx-auto mb-2"></div>
                <p className="text-gray-400 text-sm">Loading...</p>
              </div>
            ) : notifications.length === 0 ? (
              <div className="p-6 text-center text-gray-400">
                <Bell className="w-8 h-8 mx-auto mb-2 opacity-50" />
                <p>No notifications</p>
              </div>
            ) : (
              <div>
                {notifications.map((notification) => (
                  <div
                    key={notification.id}
                    className={`p-4 border-b border-white/10 hover:bg-white/5 cursor-pointer ${
                      !notification.read ? 'bg-blue-600/10' : ''
                    }`}
                    onClick={() => !notification.read && markAsRead(notification.id)}
                  >
                    <div className="flex items-start space-x-3">
                      <div className={`w-2 h-2 rounded-full mt-2 ${
                        notification.read ? 'bg-gray-600' : 'bg-blue-500'
                      }`} />
                      <div className="flex-1">
                        <p className={`text-sm font-medium ${
                          notification.read ? 'text-gray-300' : 'text-white'
                        }`}>
                          {notification.title}
                        </p>
                        <p className="text-gray-400 text-xs mt-1">
                          {notification.content}
                        </p>
                        <p className="text-gray-500 text-xs mt-2">
                          {new Date(notification.created_at).toLocaleString()}
                        </p>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </ScrollArea>

          <div className="p-2 border-t border-white/20">
            <Button
              variant="ghost"
              size="sm"
              className="w-full text-gray-400 hover:text-white hover:bg-white/10 text-xs"
              onClick={() => setShowDropdown(false)}
            >
              View all notifications
            </Button>
          </div>
        </div>
      )}
    </div>
  );
};

// Message Chat Bubble Component - Fixed positioning and functionality
export const MessageChatBubble = ({ isOpen, onClose }) => {
  const [conversations, setConversations] = useState([]);
  const [unreadMessages, setUnreadMessages] = useState(0);
  const [selectedConversation, setSelectedConversation] = useState(null);
  const [messages, setMessages] = useState([]);
  const [newMessage, setNewMessage] = useState('');
  const [isMinimized, setIsMinimized] = useState(false);
  const { toast } = useToast();

  useEffect(() => {
    if (isOpen) {
      fetchConversations();
    }
  }, [isOpen]);

  const fetchConversations = async () => {
    try {
      const response = await axios.get(`${API}/social/conversations`, {
        withCredentials: true
      });
      setConversations(response.data || []);
      
      // Calculate unread messages
      const unread = response.data.reduce((acc, conv) => acc + (conv.unread_count || 0), 0);
      setUnreadMessages(unread);
    } catch (error) {
      console.error('Error fetching conversations:', error);
      // Use mock data for development
      setConversations([
        {
          id: 1,
          participant: { name: 'Sarah Writer', id: 'user-1' },
          last_message: 'Hey! Loved your latest story!',
          timestamp: new Date().toISOString(),
          unread_count: 2
        },
        {
          id: 2,
          participant: { name: 'Mike Reader', id: 'user-2' },
          last_message: 'When is the next chapter coming out?',
          timestamp: new Date().toISOString(),
          unread_count: 0
        }
      ]);
    }
  };

  const sendMessage = async () => {
    if (!newMessage.trim() || !selectedConversation) return;

    try {
      await axios.post(`${API}/social/messages`, {
        conversation_id: selectedConversation.id,
        content: newMessage
      }, { withCredentials: true });

      // Add message to local state
      const newMsg = {
        id: Date.now(),
        content: newMessage,
        sender_id: 'current_user',
        timestamp: new Date().toISOString()
      };
      setMessages([...messages, newMsg]);
      setNewMessage('');
      
      toast({
        title: "Message Sent",
        description: "Your message has been delivered.",
      });
    } catch (error) {
      console.error('Error sending message:', error);
      toast({
        title: "Error",
        description: "Failed to send message. Please try again.",
        variant: "destructive",
      });
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center">
      <div className="bg-black border border-white/20 rounded-lg w-full max-w-4xl h-[600px] mx-4 flex overflow-hidden">
        {/* Conversations List */}
        <div className="w-1/3 border-r border-white/20">
          <div className="p-4 border-b border-white/20 flex items-center justify-between">
            <h3 className="text-white font-semibold">Messages</h3>
            <Button 
              variant="ghost" 
              size="sm"
              onClick={onClose}
              className="text-gray-400 hover:text-white"
            >
              <X className="w-4 h-4" />
            </Button>
          </div>
          
          <ScrollArea className="h-[calc(100%-60px)]">
            {conversations.map((conv) => (
              <div
                key={conv.id}
                onClick={() => setSelectedConversation(conv)}
                className={`p-4 cursor-pointer border-b border-white/10 hover:bg-white/5 ${
                  selectedConversation?.id === conv.id ? 'bg-blue-600/20' : ''
                }`}
              >
                <div className="flex items-center space-x-3">
                  <div className="w-10 h-10 bg-gray-600 rounded-full flex items-center justify-center">
                    <User className="w-5 h-5 text-gray-300" />
                  </div>
                  <div className="flex-1">
                    <div className="flex items-center justify-between">
                      <span className="text-white text-sm font-medium">{conv.participant.name}</span>
                      {conv.unread_count > 0 && (
                        <Badge className="bg-red-600 text-white text-xs">
                          {conv.unread_count}
                        </Badge>
                      )}
                    </div>
                    <p className="text-gray-400 text-xs truncate">{conv.last_message}</p>
                  </div>
                </div>
              </div>
            ))}
          </ScrollArea>
        </div>

        {/* Chat Area */}
        <div className="flex-1 flex flex-col">
          {selectedConversation ? (
            <>
              {/* Chat Header */}
              <div className="p-4 border-b border-white/20 flex items-center space-x-3">
                <div className="w-8 h-8 bg-gray-600 rounded-full flex items-center justify-center">
                  <User className="w-4 h-4 text-gray-300" />
                </div>
                <span className="text-white font-medium">{selectedConversation.participant.name}</span>
              </div>

              {/* Messages */}
              <ScrollArea className="flex-1 p-4">
                <div className="space-y-4">
                  {messages.map((msg) => (
                    <div
                      key={msg.id}
                      className={`flex ${msg.sender_id === 'current_user' ? 'justify-end' : 'justify-start'}`}
                    >
                      <div
                        className={`max-w-xs p-3 rounded-lg ${
                          msg.sender_id === 'current_user'
                            ? 'bg-blue-600 text-white'
                            : 'bg-gray-700 text-gray-100'
                        }`}
                      >
                        <p className="text-sm">{msg.content}</p>
                        <span className="text-xs opacity-70">
                          {new Date(msg.timestamp).toLocaleTimeString()}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              </ScrollArea>

              {/* Message Input */}
              <div className="p-4 border-t border-white/20">
                <div className="flex space-x-2">
                  <Input
                    value={newMessage}
                    onChange={(e) => setNewMessage(e.target.value)}
                    placeholder="Type a message..."
                    className="bg-gray-800 border-gray-600 text-white"
                    onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
                  />
                  <Button 
                    onClick={sendMessage}
                    disabled={!newMessage.trim()}
                    className="bg-blue-600 hover:bg-blue-700"
                  >
                    <Send className="w-4 h-4" />
                  </Button>
                </div>
              </div>
            </>
          ) : (
            <div className="flex-1 flex items-center justify-center">
              <p className="text-gray-400">Select a conversation to start messaging</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// Online Status Indicator Component
export const OnlineStatus = ({ status, size = "sm" }) => {
  const getStatusColor = (status) => {
    switch (status) {
      case 'online':
        return 'bg-green-500';
      case 'reading':
        return 'bg-blue-500';
      case 'appear_offline':
      case 'offline':
      default:
        return 'bg-gray-500';
    }
  };

  const sizeClasses = {
    sm: 'w-2 h-2',
    md: 'w-3 h-3',
    lg: 'w-4 h-4'
  };

  return (
    <div className="relative inline-block">
      <div className={`rounded-full ${getStatusColor(status)} ${sizeClasses[size]} border border-black`} />
    </div>
  );
};

// Friend Request Management Component - Fixed positioning and functionality
export const FriendRequestsManager = ({ isOpen, onClose }) => {
  const [requests, setRequests] = useState({ received: [], sent: [] });
  const [loading, setLoading] = useState(true);
  const { toast } = useToast();

  useEffect(() => {
    if (isOpen) {
      fetchFriendRequests();
    }
  }, [isOpen]);

  const fetchFriendRequests = async () => {
    try {
      const response = await axios.get(`${API}/social/friend-requests`, {
        withCredentials: true
      });
      setRequests(response.data);
    } catch (error) {
      console.error('Error fetching friend requests:', error);
      // Use mock data for development
      setRequests({
        received: [
          {
            id: 1,
            sender: { name: 'John Writer', id: 'user-1' },
            created_at: new Date().toISOString()
          },
          {
            id: 2,
            sender: { name: 'Alice Reader', id: 'user-2' },
            created_at: new Date().toISOString()
          }
        ],
        sent: [
          {
            id: 3,
            receiver: { name: 'Bob Author', id: 'user-3' },
            created_at: new Date().toISOString()
          }
        ]
      });
    } finally {
      setLoading(false);
    }
  };

  const handleRequest = async (requestId, action) => {
    try {
      await axios.post(`${API}/social/friend-requests/${requestId}/${action}`, {}, {
        withCredentials: true
      });

      toast({
        title: action === 'accept' ? "Friend Request Accepted" : "Friend Request Declined",
        description: `You have ${action}ed the friend request.`,
      });

      fetchFriendRequests();
    } catch (error) {
      console.error(`Error ${action}ing friend request:`, error);
      toast({
        title: "Error",
        description: `Failed to ${action} friend request. Please try again.`,
        variant: "destructive",
      });
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center">
      <div className="bg-black border border-white/20 rounded-lg w-full max-w-2xl h-[500px] mx-4 flex flex-col overflow-hidden">
        {/* Header */}
        <div className="p-4 border-b border-white/20 flex items-center justify-between">
          <h3 className="text-white font-semibold">Friend Requests</h3>
          <Button 
            variant="ghost" 
            size="sm"
            onClick={onClose}
            className="text-gray-400 hover:text-white"
          >
            <X className="w-4 h-4" />
          </Button>
        </div>

        {loading ? (
          <div className="flex-1 flex items-center justify-center">
            <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white mx-auto"></div>
          </div>
        ) : (
          <div className="flex-1 overflow-hidden">
            <Tabs defaultValue="received" className="h-full flex flex-col">
              <TabsList className="mx-4 mt-4 bg-gray-800">
                <TabsTrigger value="received" className="data-[state=active]:bg-blue-600">
                  Received ({requests.received?.length || 0})
                </TabsTrigger>
                <TabsTrigger value="sent" className="data-[state=active]:bg-blue-600">
                  Sent ({requests.sent?.length || 0})
                </TabsTrigger>
              </TabsList>

              <TabsContent value="received" className="flex-1 mx-4 mt-4">
                <ScrollArea className="h-full">
                  {requests.received?.length === 0 ? (
                    <div className="text-center text-gray-400 py-8">
                      <UserPlus className="w-12 h-12 mx-auto mb-4 opacity-50" />
                      <p>No pending friend requests</p>
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {requests.received?.map((request) => (
                        <div key={request.id} className="p-4 bg-gray-800/30 rounded-lg border border-white/10">
                          <div className="flex items-center justify-between">
                            <div className="flex items-center space-x-3">
                              <div className="w-10 h-10 bg-gray-600 rounded-full flex items-center justify-center">
                                <User className="w-5 h-5 text-gray-300" />
                              </div>
                              <div>
                                <p className="text-white font-medium">{request.sender.name}</p>
                                <p className="text-gray-400 text-sm">
                                  {new Date(request.created_at).toLocaleDateString()}
                                </p>
                              </div>
                            </div>
                            <div className="flex space-x-2">
                              <Button
                                size="sm"
                                onClick={() => handleRequest(request.id, 'accept')}
                                className="bg-green-600 hover:bg-green-700"
                              >
                                <Check className="w-4 h-4 mr-1" />
                                Accept
                              </Button>
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={() => handleRequest(request.id, 'decline')}
                                className="border-red-600 text-red-400 hover:bg-red-600/20"
                              >
                                <X className="w-4 h-4 mr-1" />
                                Decline
                              </Button>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </ScrollArea>
              </TabsContent>

              <TabsContent value="sent" className="flex-1 mx-4 mt-4">
                <ScrollArea className="h-full">
                  {requests.sent?.length === 0 ? (
                    <div className="text-center text-gray-400 py-8">
                      <Clock className="w-12 h-12 mx-auto mb-4 opacity-50" />
                      <p>No pending sent requests</p>
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {requests.sent?.map((request) => (
                        <div key={request.id} className="p-4 bg-gray-800/30 rounded-lg border border-white/10">
                          <div className="flex items-center justify-between">
                            <div className="flex items-center space-x-3">
                              <div className="w-10 h-10 bg-gray-600 rounded-full flex items-center justify-center">
                                <User className="w-5 h-5 text-gray-300" />
                              </div>
                              <div>
                                <p className="text-white font-medium">{request.receiver.name}</p>
                                <p className="text-gray-400 text-sm">
                                  Sent on {new Date(request.created_at).toLocaleDateString()}
                                </p>
                              </div>
                            </div>
                            <Badge className="bg-yellow-600/20 text-yellow-400 border-yellow-600/30">
                              <Clock className="w-3 h-3 mr-1" />
                              Pending
                            </Badge>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </ScrollArea>
              </TabsContent>
            </Tabs>
          </div>
        )}
      </div>
    </div>
  );
};