import {
  ReactElement,
  useState,
  useEffect,
  useRef,
  ChangeEvent,
  KeyboardEvent,
  useContext,
} from 'react';
import { MessageSquareText, Minus, X, Send } from 'lucide-react'; // Using lucide-react for icons
import {
  Box,
  Button,
  AppBar,
  Typography,
  useTheme,
  Fab,
  TextField,
  Paper,
  Toolbar,
  IconButton,
} from '@mui/material';
import { ChatMessage, WebSocketContext } from 'contexts/WebSocketContext';
import { AccountContext } from 'contexts/AccountContext';
import FormattedListingText from './base/FormattedListingText';

interface FloatingActionButtonProps {
  onClick: () => void;
}

const FloatingActionButton = ({ onClick }: FloatingActionButtonProps) => {
  return (
    <Fab
      color="secondary"
      aria-label="open chat"
      onClick={onClick}
      sx={{
        position: 'fixed',
        bottom: 24, // Equivalent to Tailwind's bottom-6 (24px)
        right: 24, // Equivalent to Tailwind's right-6 (24px)
        zIndex: 50, // Equivalent to Tailwind's z-50
        boxShadow: '0px 10px 15px -3px rgba(0,0,0,0.1), 0px 4px 6px -2px rgba(0,0,0,0.05)', // Tailwind shadow-lg
        '&:hover': {
          backgroundColor: '#1d4ed8', // Blue-700 equivalent
        },
      }}
    >
      <MessageSquareText size={24} />
    </Fab>
  );
};

interface ChatPaneProps {
  showChat: boolean;
  isMinimized: boolean;
  toggleMinimize: () => void;
  closeChat: () => void;
}

// Chat Pane Component
const ChatPane = ({ showChat, isMinimized, toggleMinimize, closeChat }: ChatPaneProps) => {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  // State for the current message being typed by the user
  const [inputMessage, setInputMessage] = useState<string>('');
  // State to indicate if an AI response is being loaded
  const [isLoading, setIsLoading] = useState<boolean>(false);
  // Ref for the messages container to scroll to the bottom
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const messageRef = useRef('');
  const [currentMessage, setCurrentMessage] = useState<string>('');
  const theme = useTheme();
  const { account, accountLoading } = useContext(AccountContext);

  const { subscribe, unsubscribe, socket, sendMessages } = useContext(WebSocketContext);

  useEffect(() => {
    if (accountLoading) return;
    const channelName = `ACCOUNT_ID_${account?.email}`;
    subscribe(channelName, (message: string) => {
      if (message === 'BEGINING_OF_THE_WORLD') {
      } else if (message === 'END_OF_THE_WORLD') {
        const deepCopiedMessage = structuredClone(messageRef.current);
        setMessages((prevMessages) => [...prevMessages, { text: deepCopiedMessage, sender: 'ai' }]);
        messageRef.current = '';
        setCurrentMessage(messageRef.current);
        setIsLoading(false);
      } else {
        messageRef.current += message;
        setCurrentMessage(messageRef.current);
      }
    });

    return () => {
      unsubscribe(channelName);
    };
  }, [account, subscribe, unsubscribe]);
  // Scroll to the bottom of the chat window whenever messages change
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  // Function to send a message to the AI
  const handleSendMessage = async () => {
    if (inputMessage.trim() === '') return;
    if (account !== undefined) {
      const newMessage: ChatMessage = {
        text: inputMessage,
        sender: 'user',
      };
      sendMessages([...messages, newMessage]);
      setIsLoading(true);
      setMessages((prevMessages) => [...prevMessages, newMessage]);
    }

    // const newUserMessage: ChatMessage = { text: inputMessage, sender: 'user' };
    // setMessages((prevMessages: ChatMessage[]) => [...prevMessages, newUserMessage]);
    // setInputMessage(''); // Clear input field

    // setIsLoading(true); // Show loading indicator

    // try {
    //   // Construct chat history for the API call
    //   let chatHistory = messages.map((msg) => ({
    //     role: msg.sender === 'user' ? 'user' : 'model',
    //     parts: [{ text: msg.text }],
    //   }));
    //   chatHistory.push({ role: 'user', parts: [{ text: newUserMessage.text }] });

    //   const payload = { contents: chatHistory };
    //   const apiKey = ''; // Leave this as-is; Canvas will provide the API key at runtime
    //   const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;

    //   const response = await fetch(apiUrl, {
    //     method: 'POST',
    //     headers: { 'Content-Type': 'application/json' },
    //     body: JSON.stringify(payload),
    //   });

    //   const result = await response.json();

    //   if (
    //     result.candidates &&
    //     result.candidates.length > 0 &&
    //     result.candidates[0].content &&
    //     result.candidates[0].content.parts &&
    //     result.candidates[0].content.parts.length > 0
    //   ) {
    //     const aiResponseText = result.candidates[0].content.parts[0].text;
    //     setMessages((prevMessages) => [...prevMessages, { text: aiResponseText, sender: 'ai' }]);
    //   } else {
    //     // Handle cases where the response structure is unexpected or content is missing
    //     console.error('Unexpected API response structure:', result);
    //     setMessages((prevMessages) => [
    //       ...prevMessages,
    //       { text: 'Error: Could not get a response from AI.', sender: 'ai' },
    //     ]);
    //   }
    // } catch (error) {
    //   console.error('Error fetching AI response:', error);
    //   setMessages((prevMessages) => [
    //     ...prevMessages,
    //     { text: 'Error: Failed to connect to AI.', sender: 'ai' },
    //   ]);
    // } finally {
    //   setIsLoading(false); // Hide loading indicator
    // }
  };

  if (!showChat) return null; // Don't render anything if chat is not shown

  return (
    <Box
      sx={{
        position: 'fixed',
        bottom: 24,
        right: 24,
        backgroundColor: 'white.200',
        borderRadius: '8px',
        boxShadow: '0px 20px 25px -5px rgba(0,0,0,0.1), 0px 10px 10px -5px rgba(0,0,0,0.04)', // Tailwind shadow-xl
        display: 'flex',
        flexDirection: 'column',
        transition: 'all 300ms ease-in-out',
        overflow: 'hidden',
        zIndex: 40,
        width: isMinimized ? '320px' : '384px', // w-80 (320px) vs w-96 (384px)
        height: isMinimized ? '64px' : '485px', // h-16 (64px) vs h-[600px]
        '@media (min-width: 768px)': {
          // md: breakpoint
          height: isMinimized ? '64px' : 'calc(100vh - 130px)', // md:h-[calc(100vh-80px)]
        },
        border: '1px solid',
        borderColor: 'grey.200',
      }}
    >
      {/* Chat Header */}
      <AppBar
        position="static"
        color="inherit"
        sx={{
          backgroundColor: 'background.paper',
        }}
      >
        <Toolbar variant="dense" sx={{ justifyContent: 'space-between', minHeight: '64px' }}>
          {' '}
          {/* minHeight to match h-16 for minimized */}
          <Typography variant="h6" component="div">
            AI Assistant
          </Typography>
          <Box sx={{ display: 'flex', gap: 1 }}>
            <IconButton
              color="inherit"
              onClick={toggleMinimize}
              aria-label={isMinimized ? 'Maximize chat' : 'Minimize chat'}
            >
              <Minus size={20} />
            </IconButton>
            <IconButton color="inherit" onClick={closeChat} aria-label="Close chat">
              <X size={20} />
            </IconButton>
          </Box>
        </Toolbar>
      </AppBar>

      {/* Chat Body (visible only when not minimized) */}
      {!isMinimized && (
        <Box
          sx={{
            flexGrow: 1,
            p: 2,
            overflowY: 'auto',
            backgroundColor: 'background.paper',
          }}
          className="custom-scrollbar" // Keep custom scrollbar for now
        >
          {messages.length === 0 && !isLoading && (
            <Typography variant="body2" color="text.secondary" sx={{ textAlign: 'center', mt: 5 }}>
              Start a conversation with the AI assistant!
            </Typography>
          )}
          {messages.map((msg: ChatMessage, index: number) => (
            <Box
              key={index}
              sx={{
                display: 'flex',
                mb: 2, // mb-4
                justifyContent: msg.sender === 'user' ? 'flex-end' : 'flex-start',
              }}
            >
              <Paper
                elevation={1} // shadow-sm
                sx={{
                  maxWidth: '70%',
                  p: 1.5, // p-3
                  borderRadius: '12px',
                  backgroundColor: msg.sender === 'user' ? 'primary.main' : 'grey.200',
                  color: msg.sender === 'user' ? 'white' : 'text.primary',
                  borderBottomRightRadius: msg.sender === 'user' ? 0 : '12px',
                  borderBottomLeftRadius: msg.sender === 'user' ? '12px' : 0,
                }}
              >
                {/*<Typography variant="body2">{msg.text}</Typography>*/}
                <FormattedListingText text={msg.text} />
              </Paper>
            </Box>
          ))}
          {isLoading && (
            <Box sx={{ display: 'flex', justifyContent: 'flex-start', mb: 2 }}>
              <Paper
                elevation={1}
                sx={{
                  maxWidth: '70%',
                  p: 1.5,
                  borderRadius: '12px',
                  backgroundColor: 'grey.200',
                  color: 'text.primary',
                  borderBottomLeftRadius: 0,
                }}
              >
                <Box sx={{ display: 'flex', alignItems: 'center' }}>
                  <Typography component="span" className="animate-bounce" sx={{ mr: 0.5 }}>
                    .
                  </Typography>
                  <Typography
                    component="span"
                    className="animate-bounce delay-100"
                    sx={{ mr: 0.5 }}
                  >
                    .
                  </Typography>
                  <Typography component="span" className="animate-bounce delay-200">
                    .
                  </Typography>
                </Box>
              </Paper>
            </Box>
          )}
          <div ref={messagesEndRef} /> {/* Scroll target */}
        </Box>
      )}

      {/* Chat Input (visible only when not minimized) */}
      {!isMinimized && (
        <Box
          sx={{
            flexShrink: 0,
            p: 2,
            borderTop: '1px solid',
            borderColor: 'grey.200',
            backgroundColor: 'white',
            display: 'flex',
            alignItems: 'center',
            gap: 1, // space-x-2
          }}
        >
          <TextField
            fullWidth
            variant="outlined"
            size="small"
            value={inputMessage}
            onChange={(e: ChangeEvent<HTMLInputElement>) => setInputMessage(e.target.value)}
            onKeyPress={(e: KeyboardEvent<HTMLInputElement>) =>
              e.key === 'Enter' && handleSendMessage()
            }
            placeholder="Type your message..."
            disabled={isLoading}
            sx={{
              '& .MuiOutlinedInput-root': {
                borderRadius: '8px', // rounded-lg
              },
              '& .MuiOutlinedInput-notchedOutline': {
                borderColor: 'grey.300', // border-gray-300
              },
              '& .MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline': {
                borderColor: 'primary.main', // focus:ring-blue-400 equivalent
                borderWidth: '2px',
              },
            }}
          />
          <Button
            variant="contained"
            color="primary"
            onClick={handleSendMessage}
            endIcon={<Send size={20} />}
            disabled={isLoading}
            sx={{
              p: 1.5, // p-3
              borderRadius: '8px', // rounded-lg
              boxShadow: 'none', // Remove default button shadow
              '&:hover': {
                backgroundColor: '#1d4ed8', // Blue-700 equivalent
                boxShadow: 'none',
              },
            }}
          >
            {/* Text is hidden on small screens, icon only */}
            <Typography sx={{ display: { xs: 'none', sm: 'block' } }}>Send</Typography>
          </Button>
        </Box>
      )}

      {/* Tailwind CSS Custom Scrollbar and Animation */}
      <style>
        {`
        .custom-scrollbar::-webkit-scrollbar {
          width: 8px;
        }

        .custom-scrollbar::-webkit-scrollbar-track {
          background: #f1f1f1;
          border-radius: 10px;
        }

        .custom-scrollbar::-webkit-scrollbar-thumb {
          background: #888;
          border-radius: 10px;
        }

        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
          background: #555;
        }

        @keyframes bounce {
          0%, 100% { transform: translateY(0); }
          50% { transform: translateY(-5px); }
        }

        .animate-bounce {
          animation: bounce 0.6s infinite alternate;
        }
        .animate-bounce.delay-100 { animation-delay: 0.1s; }
        .animate-bounce.delay-200 { animation-delay: 0.2s; }
        `}
      </style>
    </Box>
  );
};

const FloatingChatButton = (): ReactElement => {
  const [showChat, setShowChat] = useState<boolean>(false);
  // State to control if the chat pane is minimized
  const [isMinimized, setIsMinimized] = useState<boolean>(false);

  // Function to toggle the chat pane visibility
  const toggleChat = () => {
    setShowChat(!showChat);
    // When opening, ensure it's not minimized
    if (!showChat) {
      setIsMinimized(false);
    }
  };

  // Function to toggle minimize/maximize the chat pane
  const toggleMinimize = () => {
    setIsMinimized(!isMinimized);
  };

  // Function to close the chat pane
  const closeChat = () => {
    setShowChat(false);
    setIsMinimized(false); // Reset minimize state when closing
  };
  return (
    <div className="relative h-screen w-full font-sans bg-gray-100 flex items-center justify-center">
      {/* Floating Action Button */}
      {!showChat && <FloatingActionButton onClick={toggleChat} />}

      <ChatPane
        showChat={showChat}
        isMinimized={isMinimized}
        toggleMinimize={toggleMinimize}
        closeChat={closeChat}
      />
    </div>
  );
};

export default FloatingChatButton;
