import React, { useRef, useEffect } from "react";
import { UserMessage, AIMessage } from "./Messages";
import { useIsMobile } from "@/hooks/use-mobile";
import { useAppSelector } from "@/redux/hooks";
import { Loader2 } from "lucide-react";

interface ChatInterfaceProps {
  messages: Array<{ role: string; content: string }>;
  isListening: boolean;
}

const ChatInterface: React.FC<ChatInterfaceProps> = ({
  messages,
  isListening,
}) => {
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const isMobile = useIsMobile();
  const { isChangingChat } = useAppSelector((state) => state.chat);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  return (
    <div className="flex-1 overflow-y-auto p-2 sm:p-4 bg-black relative overflow-x-hidden scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
      {isChangingChat && (
        <div className="absolute top-0 left-0 right-0 h-2 z-50">
          <div>
            <Loader2 className="animate-spin text-white" />
          </div>
        </div>
      )}

      <div className="max-w-full sm:max-w-4xl mx-auto relative z-10 px-1 sm:px-3">
        {messages && messages.length === 0 ? (
          <div className="flex flex-col justify-center items-center h-[50vh] text-white/60 space-y-4">
            <div className="w-16 h-16 rounded-full bg-gradient-to-br from-purple-500/20 to-blue-500/20 flex items-center justify-center backdrop-blur-sm">
              <span className="text-2xl">💬</span>
            </div>
            <p className="text-lg font-light tracking-wide">
              Start a new conversation
            </p>
          </div>
        ) : (
          messages &&
          messages.length > 0 &&
          messages.map((message, index) => (
            <div key={index} className="mb-3 sm:mb-5 animate-fade-in">
              {message.role === "user" ? (
                <UserMessage
                  content={message.content}
                />
              ) : (
                <AIMessage
                  content={message.content}
                />
              )}
            </div>
          ))
        )}

        {/* {isListening && (
          <div className="flex flex-col justify-center items-center my-6 sm:my-10 bg-gradient-to-b from-black/90 to-purple-900/10 p-5 sm:p-7 rounded-2xl backdrop-blur-md border border-white/10 shadow-[0_0_25px_rgba(139,92,246,0.15)]">
            <LottieMicAnimation isListening={isListening} />
            <p className="text-white font-medium mt-4 tracking-wider animate-pulse text-lg">Listening...</p>
          </div>
        )} */}

        <div ref={messagesEndRef} />
      </div>
    </div>
  );
};

export default ChatInterface;
