import React from "react";
import {
  ResponsiveChatSystem,
  ResponsiveChatSystemConfig,
  useResponsiveChatSystem,
} from "./responsive-chat-system";
import { I18nProvider } from "./i18n-context";
import { useTheme, applyTheme, ChatbotTheme } from "./theme-config";
import { ChatbotWidget } from "./chatbot-widget";
import { SuggestedQuestions } from "./suggested-questions";
import { FloatingChatButton } from "./floating-chat-button";
import { DeviceDetectorProvider } from "./device-detector";
import { UnifiedChatSystem, ChatMode } from "./unified-chat-router";

// 메인 라이브러리 설정 인터페이스
export interface UnifiedCustomerChatLibraryConfig
  extends ResponsiveChatSystemConfig {
  // 기본 채팅 설정
  apiKey?: string;
  baseUrl?: string;
  enableTyping?: boolean;
  enableSuggestedQuestions?: boolean;

  // 언어 및 테마 설정
  defaultLanguage?: string;
  theme?: ChatbotTheme | string;
  enableThemeToggle?: boolean;

  // UI 커스터마이징
  brandName?: string;
  welcomeMessage?: string;
  placeholder?: string;

  // 플로팅 버튼 설정
  buttonPosition?: "bottom-right" | "bottom-left" | "top-right" | "top-left";
  buttonSize?: "small" | "medium" | "large";
  buttonIcon?: React.ReactNode;

  // 고급 기능
  enableAnalytics?: boolean;
  enableChatHistory?: boolean;
  maxHistorySize?: number;
}

const DEFAULT_LIBRARY_CONFIG: UnifiedCustomerChatLibraryConfig = {
  // 기본 채팅 설정
  enableTyping: true,
  enableSuggestedQuestions: true,

  // 언어 및 테마
  defaultLanguage: "ko",
  theme: "default",
  enableThemeToggle: false,

  // UI 설정
  brandName: "AgentC",
  welcomeMessage: "안녕하세요! 무엇을 도와드릴까요?",
  placeholder: "메시지를 입력하세요...",

  // 플로팅 버튼
  buttonPosition: "bottom-right",
  buttonSize: "medium",

  // 고급 기능
  enableAnalytics: false,
  enableChatHistory: true,
  maxHistorySize: 100,

  // 기본 반응형 설정
  mobileBreakpoint: 768,
  tabletBreakpoint: 1024,
  desktopBreakpoint: 1200,
  enableDebug: process.env.NODE_ENV === "development",
  defaultChatMode: "auto",
  enablePerformanceOptimization: true,
  enableEdgeCaseHandling: true,
  enableRealTimeMonitoring: true,
};

// 메인 통합 고객 채팅 라이브러리 컴포넌트
export interface UnifiedCustomerChatLibraryProps {
  config?: Partial<UnifiedCustomerChatLibraryConfig>;
  children?: React.ReactNode;
  onMessage?: (message: string) => void;
  onResponse?: (response: string) => void;
  onDeviceChange?: (deviceInfo: any) => void;
  onError?: (error: Error) => void;
  className?: string;
  style?: React.CSSProperties;
}

export const UnifiedCustomerChatLibrary: React.FC<
  UnifiedCustomerChatLibraryProps
> = ({
  config: userConfig = {},
  children,
  onMessage,
  onResponse,
  onDeviceChange,
  onError,
  className,
  style,
}) => {
  const config = { ...DEFAULT_LIBRARY_CONFIG, ...userConfig };

  // 테마 적용
  React.useEffect(() => {
    if (config.theme && typeof config.theme === "string") {
      applyTheme(config.theme as any);
    }
  }, [config.theme]);

  // 에러 핸들링
  const handleError = React.useCallback(
    (error: any) => {
      console.error("UnifiedCustomerChatLibrary Error:", error);
      if (onError) {
        onError(error instanceof Error ? error : new Error(String(error)));
      }
    },
    [onError]
  );

  return (
    <div className={className} style={style}>
      <I18nProvider defaultLanguage={config.defaultLanguage || "ko"}>
        <ResponsiveChatSystem
          config={config}
          onDeviceChange={onDeviceChange}
          onEdgeCase={handleError}
          onPerformanceIssue={(metrics) => {
            console.warn("Performance issue detected:", metrics);
          }}
        >
          <UnifiedChatSystem
            config={{
              defaultMode:
                config.defaultChatMode === "auto"
                  ? ChatMode.AUTO
                  : config.defaultChatMode === "mobile"
                  ? ChatMode.MOBILE
                  : config.defaultChatMode === "desktop"
                  ? ChatMode.DESKTOP
                  : ChatMode.AUTO,
              enableDebug: config.enableDebug,
              enableTransitions: true,
              mobileBreakpoint: config.mobileBreakpoint!,
            }}
            buttonProps={{
              position: config.buttonPosition,
              size: config.buttonSize,
            }}
          >
            <ChatbotWidget
              apiKey={config.apiKey}
              apiBaseUrl={config.baseUrl}
              enableTypingIndicator={config.enableTyping}
              title={config.brandName}
              placeholder={config.placeholder}
              onMessageSent={onMessage}
              onError={handleError}
            />
            {config.enableSuggestedQuestions && (
              <SuggestedQuestions
                onQuestionSelect={(question) => {
                  if (onMessage) {
                    onMessage(question);
                  }
                }}
              />
            )}
            {children}
          </UnifiedChatSystem>
        </ResponsiveChatSystem>
      </I18nProvider>
    </div>
  );
};

// 간단한 사용을 위한 기본 설정 컴포넌트
export interface SimpleCustomerChatProps {
  apiKey?: string;
  welcomeMessage?: string;
  language?: string;
  theme?: string;
  onMessage?: (message: string) => void;
  onResponse?: (response: string) => void;
}

export const SimpleCustomerChat: React.FC<SimpleCustomerChatProps> = ({
  apiKey,
  welcomeMessage,
  language = "ko",
  theme = "default",
  onMessage,
  onResponse,
}) => {
  return (
    <UnifiedCustomerChatLibrary
      config={{
        apiKey,
        welcomeMessage,
        defaultLanguage: language,
        theme,
        enableSuggestedQuestions: true,
        enablePerformanceOptimization: true,
        enableEdgeCaseHandling: true,
      }}
      onMessage={onMessage}
      onResponse={onResponse}
    />
  );
};

// 고급 사용자를 위한 커스터마이징 가능한 컴포넌트
export interface AdvancedCustomerChatProps
  extends UnifiedCustomerChatLibraryProps {
  customComponents?: {
    FloatingButton?: React.ComponentType<any>;
    ChatWidget?: React.ComponentType<any>;
    SuggestedQuestions?: React.ComponentType<any>;
  };
}

export const AdvancedCustomerChat: React.FC<AdvancedCustomerChatProps> = ({
  customComponents,
  ...props
}) => {
  // 커스텀 컴포넌트가 제공된 경우 해당 컴포넌트들을 사용
  if (customComponents) {
    return (
      <UnifiedCustomerChatLibrary {...props}>
        {customComponents.FloatingButton && <customComponents.FloatingButton />}
        {customComponents.ChatWidget && <customComponents.ChatWidget />}
        {customComponents.SuggestedQuestions && (
          <customComponents.SuggestedQuestions />
        )}
        {props.children}
      </UnifiedCustomerChatLibrary>
    );
  }

  return <UnifiedCustomerChatLibrary {...props} />;
};

// 훅을 통한 채팅 상태 관리
export const useCustomerChat = () => {
  const responsiveChat = useResponsiveChatSystem();
  const theme = useTheme();

  return {
    ...responsiveChat,
    theme,
    // 편의 메서드들
    sendMessage: (message: string) => {
      // 실제 메시지 전송 로직
      console.log("Sending message:", message);
    },
    clearHistory: () => {
      // 채팅 히스토리 클리어 로직
      console.log("Clearing chat history");
    },
    changeTheme: (themeName: string) => {
      applyTheme(themeName as any);
    },
  };
};

// 디버그 및 개발자 도구
export const ChatLibraryDebugInfo: React.FC = () => {
  const chatState = useCustomerChat();

  if (process.env.NODE_ENV !== "development") {
    return null;
  }

  return (
    <div
      style={{
        position: "fixed",
        top: 10,
        left: 10,
        background: "rgba(0,0,0,0.8)",
        color: "white",
        padding: "10px",
        borderRadius: "5px",
        fontSize: "12px",
        zIndex: 10000,
        maxWidth: "300px",
      }}
    >
      <h4>Chat Library Debug Info</h4>
      <div>Device: {chatState.deviceInfo.type}</div>
      <div>
        Screen: {chatState.deviceInfo.screenWidth}x
        {chatState.deviceInfo.screenHeight}
      </div>
      <div>Orientation: {chatState.orientation}</div>
      <div>Touch Device: {chatState.isTouchDevice ? "Yes" : "No"}</div>
      <div>Keyboard Visible: {chatState.isKeyboardVisible ? "Yes" : "No"}</div>
      <div>Connection: {chatState.connectionType}</div>
      <div>
        Battery: {chatState.batteryLevel}% (
        {chatState.isCharging ? "Charging" : "Not Charging"})
      </div>
    </div>
  );
};

// 기본 익스포트
export default UnifiedCustomerChatLibrary;

// 주요 훅들 재익스포트
export { useResponsiveChatSystem } from "./responsive-chat-system";
export { useTheme } from "./theme-config";
