import { useSocket } from '@/hooks/useSocket';
import { Mic, Paperclip, Send, Smile } from 'lucide-react';
import { useEffect, useRef, useState, type FC, type FormEvent } from 'react';
import { toast } from 'sonner';
import { Button } from './ui/button';
import { Input } from './ui/input';

type MessageInputProps = {
  roomId: string;
};

export const MessageInput: FC<MessageInputProps> = ({ roomId }) => {
  const [message, setMessage] = useState('');
  const [isRateLimited, setIsRateLimited] = useState(false);
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  const [isFocused, setIsFocused] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const { socket } = useSocket();

  useEffect(() => {
    if (!socket) return;

    const handleRateLimitExceeded = (data: {
      message: string;
      remainingTime?: number;
    }) => {
      setIsRateLimited(true);
      toast.error(data.message);

      const resetTime = data.remainingTime ?? 60000;
      setTimeout(() => {
        setIsRateLimited(false);
      }, resetTime);
    };

    socket.on('rate_limit_exceeded', handleRateLimitExceeded);

    return () => {
      socket.off('rate_limit_exceeded', handleRateLimitExceeded);
    };
  }, [socket, toast]);

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

    if (!message.trim() || !socket || isRateLimited) return;

    socket.emit('send_message', {
      roomId,
      content: message.trim(),
    });

    setMessage('');
  };

  // Function to handle emoji selection (placeholder for now)
  const handleEmojiClick = (emoji: string) => {
    setMessage((prev) => prev + emoji);
    inputRef.current?.focus();
    setShowEmojiPicker(false);
  };

  return (
    <div className="p-4 border-t border-gray-200 bg-white dark:bg-gray-900 transition-all duration-200">
      <div className="max-w-4xl mx-auto">
        <form onSubmit={handleSubmit} className="relative">
          <div
            className={`flex items-center space-x-2 p-1 rounded-full border ${
              isFocused ? 'border-blue-400 shadow-sm' : 'border-gray-300'
            } bg-white dark:bg-gray-800 transition-all duration-200`}
          >
            <Button
              type="button"
              variant="ghost"
              size="icon"
              className="rounded-full h-9 w-9 text-gray-500 hover:text-gray-700 hover:bg-gray-100 dark:hover:bg-gray-700"
              onClick={() => setShowEmojiPicker((prev) => !prev)}
            >
              <Smile className="h-5 w-5" />
            </Button>

            <Button
              type="button"
              variant="ghost"
              size="icon"
              className="rounded-full h-9 w-9 text-gray-500 hover:text-gray-700 hover:bg-gray-100 dark:hover:bg-gray-700"
            >
              <Paperclip className="h-5 w-5" />
            </Button>

            <Input
              ref={inputRef}
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              onFocus={() => setIsFocused(true)}
              onBlur={() => setIsFocused(false)}
              placeholder={
                isRateLimited
                  ? 'Rate limited - please wait...'
                  : 'Type your message...'
              }
              disabled={isRateLimited}
              className="flex-1 border-0 focus-visible:ring-0 focus-visible:ring-offset-0 bg-transparent py-2 px-3"
            />

            {message.trim() ? (
              <Button
                type="submit"
                size="icon"
                disabled={!message.trim() || isRateLimited}
                className="rounded-full h-9 w-9 bg-blue-500 hover:bg-blue-600 text-white"
              >
                <Send className="h-4 w-4" />
              </Button>
            ) : (
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="rounded-full h-9 w-9 text-gray-500 hover:text-gray-700 hover:bg-gray-100 dark:hover:bg-gray-700"
              >
                <Mic className="h-5 w-5" />
              </Button>
            )}
          </div>

          {/* Emoji picker placeholder - you'd need to implement or use a library like emoji-mart */}
          {showEmojiPicker && (
            <div className="absolute bottom-full mb-2 p-2 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700">
              <div className="grid grid-cols-8 gap-1">
                {['😀', '😂', '❤️', '👍', '🎉', '🔥', '👏', '😢'].map(
                  (emoji) => (
                    <button
                      key={emoji}
                      type="button"
                      onClick={() => handleEmojiClick(emoji)}
                      className="p-1 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md transition-colors"
                    >
                      {emoji}
                    </button>
                  )
                )}
              </div>
            </div>
          )}
        </form>

        {isFocused && !isRateLimited && (
          <div className="mt-1 text-xs text-gray-500 dark:text-gray-400 flex justify-between">
            <span>Press Enter to send</span>
            <span>{message.length} / 2000</span>
          </div>
        )}
      </div>
    </div>
  );
};
