import { useState, useEffect, useRef } from "react";
import { type LoaderFunctionArgs } from "react-router";
import { useNavigate } from "react-router";
import { authenticate } from "../shopify.server";
import { ChatProvider, useChatContext } from "../components/providers/chat-context";
import { useGlobalContext } from "../components/providers/global-context";
import ChatMessage from "app/features/test-chat/components/chat-message";
import { sendChatMessage } from "../utils/chat-api";
import { BsChevronLeft } from "react-icons/bs";
import { Message } from "../types/global-types";
import styles from "app/features/test-chat/components/test-chat.module.css";

export const loader = async ({ request }: LoaderFunctionArgs) => {
  await authenticate.admin(request);
  return {};
};

export default function TestChat() {
  const { agent } = useGlobalContext();
  
  return (
    <ChatProvider initialMessage={agent?.chat_first_message || "Hello! How can I help you today?"}>
      <TestChatContent />
    </ChatProvider>
  );
}

function TestChatContent() {
  const { messages, chatId, isLoading, addMessage, setChatId, setLoading } = useChatContext();
  const { agent } = useGlobalContext();
  const [inputValue, setInputValue] = useState("");
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const navigate = useNavigate();

  console.log(agent)

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

  const scrollToBottom = () => {
    // Use setTimeout to ensure DOM has updated
    setTimeout(() => {
      messagesEndRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });
    }, 100);
  };

  const handleSendMessage = async () => {
    if (!inputValue.trim()) return;
    if (isLoading) return;
    if (!agent?._id || !agent?.script_data?.key) {
      console.error("Agent configuration missing");
      return;
    }

    const messageText = inputValue.trim();
    setInputValue("");
    setLoading(true);

    try {
      // Add user message immediately
      const userMessage: Message = {
        id: `user-${Date.now()}`,
        text: messageText,
        sender: "user",
        timestamp: new Date(),
      };
      addMessage(userMessage);

      // Send message to API with chat_id (will be undefined on first user message)
      const response = await sendChatMessage({
        message: messageText,
        chatId: chatId || undefined,
        agentId: agent._id,
        secretKey: agent.script_data.key,
        userName: agent.name,
      });

      // Set chat_id from the first response
      if (!chatId && response.data.chat_id) {
        setChatId(response.data.chat_id);
      }

      // Add agent response
      const agentMessage: Message = {
        id: `agent-${Date.now()}`,
        text: response.data.ai_response.chatresponseanswer,
        sender: "agent",
        timestamp: new Date(),
        products: response.data.ai_response.shopifyRecommendation?.products || [],
      };
      addMessage(agentMessage);
    } catch (error) {
      console.error("Error sending message:", error);
      
      // Add error message
      const errorMessage: Message = {
        id: `error-${Date.now()}`,
        text: "Sorry, I encountered an error. Please try again.",
        sender: "agent",
        timestamp: new Date(),
      };
      addMessage(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  return (
    <div className={styles.pageContainer}>
      {/* Page Header with Back Button */}
      <div className={styles.pageHeader}>
        <button className={styles.backButton} onClick={() => navigate("/app")}>
          <BsChevronLeft size={20} />
          <span>Back</span>
        </button>
        <h2 className={styles.pageTitle}>Test Live Agent Chat</h2>
      </div>

      <div className={styles.chatContainer}>
        {/* Header */}
        <div className={styles.header}>
          <div className={styles.iconWrapper}>
            <svg
              width="13"
              height="13"
              viewBox="0 0 13 13"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M8.50977 6.88455C9.04081 6.46674 9.42843 5.8938 9.61869 5.24543C9.80895 4.59707 9.79239 3.90553 9.57132 3.26701C9.35024 2.6285 8.93565 2.07476 8.38522 1.68285C7.83479 1.29093 7.17588 1.08032 6.50018 1.08032C5.82448 1.08032 5.16558 1.29093 4.61514 1.68285C4.06471 2.07476 3.65012 2.6285 3.42905 3.26701C3.20797 3.90553 3.19142 4.59707 3.38168 5.24543C3.57194 5.8938 3.95955 6.46674 4.4906 6.88455C3.58064 7.24911 2.78667 7.85378 2.19333 8.63409C1.59999 9.41439 1.22953 10.3411 1.12143 11.3154C1.11361 11.3865 1.11987 11.4585 1.13986 11.5272C1.15985 11.5959 1.19318 11.66 1.23795 11.7159C1.32836 11.8286 1.45986 11.9008 1.60351 11.9166C1.74717 11.9324 1.89123 11.8905 2.00398 11.8001C2.11674 11.7097 2.18896 11.5782 2.20476 11.4345C2.32371 10.3757 2.82859 9.39778 3.62297 8.68764C4.41734 7.97751 5.4455 7.58494 6.51102 7.58494C7.57653 7.58494 8.60469 7.97751 9.39906 8.68764C10.1934 9.39778 10.6983 10.3757 10.8173 11.4345C10.832 11.5676 10.8955 11.6906 10.9955 11.7796C11.0956 11.8686 11.225 11.9174 11.3589 11.9166H11.4185C11.5605 11.9003 11.6903 11.8285 11.7796 11.7169C11.8689 11.6053 11.9104 11.4629 11.8952 11.3208C11.7866 10.3437 11.4141 9.41467 10.8177 8.63316C10.2213 7.85165 9.42351 7.24718 8.50977 6.88455ZM6.50018 6.49997C6.07166 6.49997 5.65275 6.37289 5.29645 6.13482C4.94014 5.89674 4.66243 5.55835 4.49844 5.16245C4.33445 4.76654 4.29155 4.3309 4.37515 3.9106C4.45875 3.49031 4.6651 3.10425 4.96812 2.80123C5.27113 2.49822 5.65719 2.29187 6.07749 2.20826C6.49778 2.12466 6.93342 2.16757 7.32933 2.33156C7.72524 2.49555 8.06362 2.77326 8.3017 3.12956C8.53978 3.48587 8.66685 3.90477 8.66685 4.3333C8.66685 4.90794 8.43858 5.45904 8.03225 5.86536C7.62592 6.27169 7.07482 6.49997 6.50018 6.49997Z"
                fill="#9100DF"
              />
            </svg>
          </div>
          <h1 className={styles.headerTitle}>
            {agent ? agent.name : "Loading Agent..."}
          </h1>
        </div>

        {/* Messages Area */}
        <div className={styles.messagesArea}>
          {messages.map((message) => (
            <ChatMessage key={message.id} message={message} />
          ))}
          {isLoading && (
            <div className={styles.loadingMessage}>
              <div className={styles.loadingBubble}>
                <div className={styles.loadingDots}>
                  <div className={styles.dot}></div>
                  <div className={styles.dot}></div>
                  <div className={styles.dot}></div>
                </div>
              </div>
            </div>
          )}
          <div ref={messagesEndRef} />
        </div>

        {/* Input Area */}
        <div className={styles.inputContainer}>
          <div className={styles.inputWrapper}>
            <textarea
              ref={textareaRef}
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyDown={handleKeyPress}
              placeholder="Enter your message"
              className={styles.textarea}
              rows={1}
            />

            <button
              className={styles.sendButton}
              onClick={handleSendMessage}
              disabled={isLoading}
              type="button"
            >
              <svg
                width="20"
                height="20"
                viewBox="0 0 24 24"
                fill="currentColor"
                stroke="none"
              >
                <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
