"use client";

import React, { useState, useCallback } from "react";
import { FloatingChatButton } from "./floating-chat-button";
import { DesktopChatModal } from "./desktop-chat-modal";
import { I18nProvider } from "./i18n-context";
import { ModalStateProvider, useModalState } from "./modal-state-context";

interface DesktopChatbotIntegratedProps {
  apiEndpoint?: string;
  language?: string;
  theme?: "light" | "dark";
  position?: "bottom-right" | "bottom-left" | "top-right" | "top-left";
  className?: string;
}

// Inner component that uses the modal state context and real API
function DesktopChatbotInner({
  apiEndpoint = "/api/rag/answer",
  className = "",
}: Pick<DesktopChatbotIntegratedProps, "apiEndpoint" | "className">) {
  const { modalState, openModal, addMessage } = useModalState();
  const [isTyping, setIsTyping] = useState(false);

  const handleSendMessage = useCallback(
    async (message: string) => {
      try {
        setIsTyping(true);

        // Call real RAG API
        const response = await fetch(apiEndpoint, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            question: message,
            sessionId: modalState.isOpen ? "desktop-modal-session" : undefined,
          }),
        });

        if (!response.ok) {
          throw new Error(
            `API call failed: ${response.status} ${response.statusText}`
          );
        }

        const data = await response.json();

        // Add AI response to state
        addMessage({
          content: data.answer || data.response || "응답을 받지 못했습니다.",
          sender: "ai",
          type: "text",
        });
      } catch (error) {
        console.error("Failed to send message:", error);

        // Add error message to state
        addMessage({
          content:
            "죄송합니다. 메시지를 처리하는 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.",
          sender: "ai",
          type: "error",
        });
      } finally {
        setIsTyping(false);
      }
    },
    [addMessage, apiEndpoint, modalState.isOpen]
  );

  const handleButtonClick = useCallback(() => {
    openModal();
  }, [openModal]);

  return (
    <div className={`relative ${className}`}>
      {/* Floating Chat Button */}
      <FloatingChatButton
        onClick={handleButtonClick}
        position="bottom-right"
        size="lg"
        className="z-40"
        ariaLabel="AI 어시스턴트와 채팅하기"
      />

      {/* Desktop Chat Modal */}
      <DesktopChatModal
        onSendMessage={handleSendMessage}
        isTyping={isTyping}
        title="AI 어시스턴트"
        placeholder="질문을 입력하세요..."
        showSuggestedQuestions={true}
        suggestedQuestionsContext="welcome"
        allowMinimize={true}
        width="800px"
        height="600px"
      />
    </div>
  );
}

// Main component with providers and full RAG API integration
export function DesktopChatbotIntegrated({
  apiEndpoint = "/api/rag/answer",
  language = "ko",
  theme = "light",
  position = "bottom-right",
  className = "",
}: DesktopChatbotIntegratedProps) {
  return (
    <I18nProvider defaultLanguage={language}>
      <ModalStateProvider
        persistToStorage={true}
        maxSessions={10}
        sessionTimeout={24 * 60 * 60 * 1000} // 24 hours
      >
        <DesktopChatbotInner apiEndpoint={apiEndpoint} className={className} />
      </ModalStateProvider>
    </I18nProvider>
  );
}

export default DesktopChatbotIntegrated;

// 사용 예제:
/*
import DesktopChatbotIntegrated from "@/components/chatbot/customer/desktop-chatbot-integrated";

function MyPage() {
  return (
    <div>
      <h1>My Application</h1>
      <p>Some content here...</p>
      
      <DesktopChatbotIntegrated
        apiEndpoint="/api/rag/answer"
        language="ko"
        theme="light"
        position="bottom-right"
        className="custom-chatbot-styles"
      />
    </div>
  );
}
*/
