"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";
// import { ChatbotAPI } from "@/lib/chatbot/client/api";

// Inner component that uses the modal state context
function DesktopChatbotInner() {
  const { modalState, openModal, addMessage } = useModalState();
  const [isTyping, setIsTyping] = useState(false);

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

        // Simulate API call
        await new Promise((resolve) => setTimeout(resolve, 1000));

        // Add AI response to state
        addMessage({
          content: `AI 응답: ${message}에 대한 답변입니다.`,
          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]
  );

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

  return (
    <div className="relative">
      {/* Floating Chat Button */}
      <FloatingChatButton
        onClick={handleButtonClick}
        position="bottom-right"
        size="lg"
        className="z-40"
        ariaLabel="채팅 시작하기"
      />

      {/* 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
export function DesktopChatbotExample() {
  return (
    <I18nProvider defaultLanguage="ko">
      <ModalStateProvider
        persistToStorage={true}
        maxSessions={10}
        sessionTimeout={24 * 60 * 60 * 1000} // 24 hours
      >
        <DesktopChatbotInner />
      </ModalStateProvider>
    </I18nProvider>
  );
}

export default DesktopChatbotExample;

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

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