import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { DeviceDetectorProvider, useDeviceDetection, DeviceType } from './device-detector';

// Simplified chat interface types
export enum ChatMode {
  DESKTOP = 'desktop',
  MOBILE = 'mobile',
  AUTO = 'auto'
}

export interface ChatState {
  isOpen: boolean;
  mode: ChatMode;
  sessionId: string;
}

// Router configuration
export interface UnifiedChatRouterConfig {
  defaultMode: ChatMode;
  enableDebug: boolean;
  enableTransitions: boolean;
  mobileBreakpoint: number;
}

const DEFAULT_CONFIG: UnifiedChatRouterConfig = {
  defaultMode: ChatMode.AUTO,
  enableDebug: false,
  enableTransitions: true,
  mobileBreakpoint: 768
};

// Context for chat router
interface UnifiedChatRouterContextType {
  chatState: ChatState;
  config: UnifiedChatRouterConfig;
  openChat: () => void;
  closeChat: () => void;
  toggleChat: () => void;
  switchMode: (mode: ChatMode) => void;
}const UnifiedChatRouterContext = React.createContext<UnifiedChatRouterContextType | undefined>(undefined);

// Hook to use the chat router
export const useUnifiedChatRouter = (): UnifiedChatRouterContextType => {
  const context = React.useContext(UnifiedChatRouterContext);
  if (context === undefined) {
    throw new Error('useUnifiedChatRouter must be used within a UnifiedChatRouterProvider');
  }
  return context;
};

// Utility functions
const generateSessionId = (): string => {
  return `chat_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
};

const determineChatMode = (deviceInfo: any, config: UnifiedChatRouterConfig): ChatMode => {
  if (config.defaultMode !== ChatMode.AUTO) {
    return config.defaultMode;
  }

  // Auto-detect based on device
  if (deviceInfo.type === DeviceType.MOBILE || 
      (deviceInfo.isTouchDevice && deviceInfo.screenWidth <= config.mobileBreakpoint)) {
    return ChatMode.MOBILE;
  }

  return ChatMode.DESKTOP;
};

// Main router provider
interface UnifiedChatRouterProviderProps {
  children: React.ReactNode;
  config?: Partial<UnifiedChatRouterConfig>;
}export const UnifiedChatRouterProvider: React.FC<UnifiedChatRouterProviderProps> = ({
  children,
  config: userConfig = {}
}) => {
  const config = useMemo(() => ({ ...DEFAULT_CONFIG, ...userConfig }), [userConfig]);
  const { deviceInfo } = useDeviceDetection();
  
  // Chat state
  const [chatState, setChatState] = useState<ChatState>(() => ({
    isOpen: false,
    mode: determineChatMode(deviceInfo, config),
    sessionId: generateSessionId()
  }));

  // Update mode when device changes
  useEffect(() => {
    if (config.defaultMode === ChatMode.AUTO) {
      const newMode = determineChatMode(deviceInfo, config);
      if (newMode !== chatState.mode) {
        setChatState(prev => ({ ...prev, mode: newMode }));
      }
    }
  }, [deviceInfo, config, chatState.mode]);

  // Chat control functions
  const openChat = useCallback(() => {
    setChatState(prev => ({ ...prev, isOpen: true }));
  }, []);

  const closeChat = useCallback(() => {
    setChatState(prev => ({ ...prev, isOpen: false }));
  }, []);

  const toggleChat = useCallback(() => {
    setChatState(prev => ({ ...prev, isOpen: !prev.isOpen }));
  }, []);  const switchMode = useCallback((mode: ChatMode) => {
    setChatState(prev => ({ ...prev, mode }));
  }, []);

  // Context value
  const contextValue: UnifiedChatRouterContextType = {
    chatState,
    config,
    openChat,
    closeChat,
    toggleChat,
    switchMode
  };

  return (
    <UnifiedChatRouterContext.Provider value={contextValue}>
      {children}
      <ChatRenderer />
      {config.enableDebug && <DebugPanel />}
    </UnifiedChatRouterContext.Provider>
  );
};

// Chat renderer component
const ChatRenderer: React.FC = () => {
  const { chatState } = useUnifiedChatRouter();

  if (!chatState.isOpen) return null;

  return (
    <div>
      {chatState.mode === ChatMode.MOBILE && (
        <MobileChatInterface sessionId={chatState.sessionId} />
      )}
      {chatState.mode === ChatMode.DESKTOP && (
        <DesktopChatInterface sessionId={chatState.sessionId} />
      )}
    </div>
  );
};// Mobile chat interface
interface MobileChatInterfaceProps {
  sessionId: string;
}

const MobileChatInterface: React.FC<MobileChatInterfaceProps> = ({ sessionId }) => {
  const { closeChat } = useUnifiedChatRouter();

  return (
    <div style={{
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      backgroundColor: 'white',
      zIndex: 9999,
      display: 'flex',
      flexDirection: 'column'
    }}>
      <div style={{
        padding: '16px',
        borderBottom: '1px solid #e0e0e0',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between'
      }}>
        <h2 style={{ margin: 0, fontSize: '18px' }}>Chat Support</h2>
        <button onClick={closeChat} style={{
          background: 'none',
          border: 'none',
          fontSize: '24px',
          cursor: 'pointer',
          padding: '8px'
        }}>×</button>
      </div>
      <div style={{ flex: 1, padding: '16px' }}>
        <div style={{ padding: '20px', textAlign: 'center', color: '#666' }}>
          Mobile Chat Interface<br />Session: {sessionId}
        </div>
      </div>
    </div>
  );
};// Desktop chat interface
interface DesktopChatInterfaceProps {
  sessionId: string;
}

const DesktopChatInterface: React.FC<DesktopChatInterfaceProps> = ({ sessionId }) => {
  const { closeChat } = useUnifiedChatRouter();

  return (
    <div style={{
      position: 'fixed',
      bottom: '100px',
      right: '20px',
      width: '400px',
      height: '500px',
      backgroundColor: 'white',
      border: '1px solid #ddd',
      borderRadius: '12px',
      boxShadow: '0 8px 32px rgba(0,0,0,0.15)',
      zIndex: 9999,
      display: 'flex',
      flexDirection: 'column'
    }}>
      <div style={{
        padding: '16px',
        borderBottom: '1px solid #e0e0e0',
        borderRadius: '12px 12px 0 0',
        backgroundColor: '#f8f9fa',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between'
      }}>
        <h3 style={{ margin: 0, fontSize: '16px' }}>Chat Support</h3>
        <button onClick={closeChat} style={{
          background: 'none',
          border: 'none',
          fontSize: '20px',
          cursor: 'pointer',
          padding: '4px'
        }}>×</button>
      </div>
      <div style={{ flex: 1, padding: '16px' }}>
        <div style={{ padding: '20px', textAlign: 'center', color: '#666' }}>
          Desktop Chat Interface<br />Session: {sessionId}
        </div>
      </div>
    </div>
  );
};// Debug panel
const DebugPanel: React.FC = () => {
  const { chatState } = useUnifiedChatRouter();
  const { deviceInfo } = useDeviceDetection();

  if (process.env.NODE_ENV === 'production') return null;

  return (
    <div style={{
      position: 'fixed',
      top: '10px',
      left: '10px',
      background: 'rgba(0, 0, 0, 0.8)',
      color: 'white',
      padding: '10px',
      borderRadius: '5px',
      fontSize: '12px',
      fontFamily: 'monospace',
      zIndex: 10000,
      maxWidth: '300px'
    }}>
      <div style={{ fontWeight: 'bold', marginBottom: '5px' }}>Unified Chat Router Debug</div>
      <div>Mode: {chatState.mode}</div>
      <div>Open: {chatState.isOpen ? 'Yes' : 'No'}</div>
      <div>Device: {deviceInfo.type}</div>
      <div>Touch: {deviceInfo.isTouchDevice ? 'Yes' : 'No'}</div>
      <div>Screen: {deviceInfo.screenWidth}x{deviceInfo.screenHeight}</div>
      <div>Session: {chatState.sessionId.slice(-8)}</div>
    </div>
  );
};

// Unified floating chat button
interface UnifiedFloatingChatButtonProps {
  position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';
  size?: 'small' | 'medium' | 'large';
  className?: string;
}export const UnifiedFloatingChatButton: React.FC<UnifiedFloatingChatButtonProps> = ({
  position = 'bottom-right',
  size = 'medium',
  className
}) => {
  const { toggleChat, chatState } = useUnifiedChatRouter();

  const getPositionStyles = () => {
    const positions = {
      'bottom-right': { bottom: '20px', right: '20px' },
      'bottom-left': { bottom: '20px', left: '20px' },
      'top-right': { top: '20px', right: '20px' },
      'top-left': { top: '20px', left: '20px' }
    };
    return positions[position];
  };

  const getSizeStyles = () => {
    const sizes = {
      small: { width: '48px', height: '48px', fontSize: '20px' },
      medium: { width: '56px', height: '56px', fontSize: '24px' },
      large: { width: '64px', height: '64px', fontSize: '28px' }
    };
    return sizes[size];
  };

  return (
    <button
      onClick={toggleChat}
      className={className}
      style={{
        position: 'fixed',
        ...getPositionStyles(),
        ...getSizeStyles(),
        backgroundColor: chatState.isOpen ? '#dc3545' : '#007bff',
        color: 'white',
        border: 'none',
        borderRadius: '50%',
        cursor: 'pointer',
        boxShadow: '0 4px 12px rgba(0,0,0,0.2)',
        zIndex: 9998,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        transition: 'all 0.3s ease'
      }}
      title={chatState.isOpen ? 'Close Chat' : 'Open Chat'}
    >
      {chatState.isOpen ? '×' : '💬'}
    </button>
  );
};// Complete unified chat system
interface UnifiedChatSystemProps {
  config?: Partial<UnifiedChatRouterConfig>;
  buttonProps?: Partial<UnifiedFloatingChatButtonProps>;
  children?: React.ReactNode;
}

export const UnifiedChatSystem: React.FC<UnifiedChatSystemProps> = ({
  config,
  buttonProps,
  children
}) => {
  return (
    <DeviceDetectorProvider>
      <UnifiedChatRouterProvider config={config}>
        {children}
        <UnifiedFloatingChatButton {...buttonProps} />
      </UnifiedChatRouterProvider>
    </DeviceDetectorProvider>
  );
};

export default UnifiedChatSystem;