import React, { useEffect, useState } from 'react'
import MessageList from './MessageList'
import MessageInput from './MessageInput'
import Avatar from './Avatar'
import { useLocalization } from '@/hooks/useLocalization'
import { ChatConfig, Conversation } from '@/types'

interface ChatWindowProps {
  conversation: Conversation | null
  config: ChatConfig
  isLoading: boolean
  error: string | null
  onClose: () => void
  onSendMessage: (message: string) => void
  onEmailSubmit?: (email: string) => void
  onWhatsAppClick?: () => void
  aiName?: string
  aiAvatarUrl?: string
  buttonRef: React.RefObject<HTMLDivElement>
}

const ChatWindow: React.FC<ChatWindowProps> = ({
  conversation,
  config,
  isLoading,
  error,
  onClose,
  onSendMessage,
  onEmailSubmit,
  onWhatsAppClick,
  aiName,
  aiAvatarUrl,
  buttonRef
}) => {
  const { t } = useLocalization()
  const [windowPosition, setWindowPosition] = useState<React.CSSProperties>(() => (
    config.position === 'center'
      ? { top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }
      : {}
  ))

  // 动态计算窗口位置
  useEffect(() => {
    const calculatePosition = () => {
      // Center mode: render in the center of the viewport
      if (config.position === 'center') {
        const style: React.CSSProperties = {
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)'
        }
        setWindowPosition(style)
        return
      }

      if (!buttonRef.current) return

      const buttonRect = buttonRef.current.getBoundingClientRect()
      const windowWidth = window.innerWidth
      const windowHeight = window.innerHeight
      // 聊天窗口的尺寸（与CSS类对应）
      const chatWindowWidth = windowWidth < 640 ? 320 : 384 // w-80 sm:w-96
      const chatWindowHeight = windowWidth < 640 ? 384 : 448 // h-96 sm:h-[28rem]

      // 间距
      const gap = 20 // 8px gap between button and window

      const style: React.CSSProperties = {}

      switch (config.position) {
        case 'bottom-right':
          style.bottom = `${windowHeight - buttonRect.top + gap}px`
          style.right = `${windowWidth - buttonRect.left - buttonRect.width}px`
          break
        case 'bottom-left':
          style.bottom = `${windowHeight - buttonRect.top + gap}px`
          style.left = `${buttonRect.left}px`
          break
        case 'top-right':
          style.top = `${buttonRect.bottom + gap}px`
          style.right = `${windowWidth - buttonRect.left - buttonRect.width}px`
          break
        case 'top-left':
          style.top = `${buttonRect.bottom + gap}px`
          style.left = `${buttonRect.right - buttonRect.width }px`
          break
        default:
          // 默认为 bottom-right
          style.bottom = `${windowHeight - buttonRect.top + gap}px`
          style.right = `${windowWidth - buttonRect.left}px`
          break
      }

      // 确保窗口不会超出视窗边界
      if (style.left && parseFloat(style.left as string) < 0) {
        style.left = '8px'
      }
      if (style.right && parseFloat(style.right as string) < 0) {
        style.right = '8px'
      }
      if (style.top && parseFloat(style.top as string) < 0) {
        style.top = '8px'
      }
      if (style.bottom && parseFloat(style.bottom as string) < 0) {
        style.bottom = '8px'
      }

      // 检查右边界
      if (style.left) {
        const leftValue = parseFloat(style.left as string)
        if (leftValue + chatWindowWidth > windowWidth) {
          style.left = `${windowWidth - chatWindowWidth - 8}px`
        }
      }

      // 检查下边界
      if (style.top) {
        const topValue = parseFloat(style.top as string)
        if (topValue + chatWindowHeight > windowHeight) {
          style.top = `${windowHeight - chatWindowHeight - 8}px`
        }
      }

      setWindowPosition(style)
    }

    // 初始计算
    calculatePosition()

    // 监听窗口大小变化
    window.addEventListener('resize', calculatePosition)

    return () => {
      window.removeEventListener('resize', calculatePosition)
    }
  }, [buttonRef, config.position])
  
  const animationClass = config.position === 'center' ? 'lfc-animate-fade-in' : 'lfc-animate-slide-up'
  const getPositioningClasses = () => {
    return 'lfc-fixed lfc-z-40'
  }

  const getVisibilityClasses = () => {
    // Center modal should always be visible regardless of button visibility settings
    if (config.position === 'center') {
      return 'lfc-flex'
    }
    const classes = []

    if (config.showOnMobile === false) {
      classes.push('lfc-hidden md:lfc-flex')
    }

    if (config.showOnDesktop === false) {
      classes.push('md:lfc-hidden')
    }

    if (classes.length === 0) {
      classes.push('lfc-flex')
    }

    return classes.join(' ')
  }

  const getWindowStyle = () => {
    const baseStyle: React.CSSProperties = {}

    if (config.primaryColor) {
      baseStyle.borderTopColor = config.primaryColor
    }

    return baseStyle
  }

  return (
    <div
      className={`
        ai-cs-chat-window is-open
        ${getPositioningClasses()} lfc-w-80 sm:lfc-w-96 lfc-h-96 sm:lfc-h-[28rem]
        lfc-bg-bg-base lfc-rounded-lg lfc-shadow-xl lfc-border lfc-border-border-subtle
        ${getVisibilityClasses()}
        ${animationClass}
        lfc-flex-col
        lfc-border-t-4
      `}
      style={{ ...getWindowStyle(), ...windowPosition }}
    >
      {/* Header */}
      <div
        className="lfc-flex lfc-items-center lfc-justify-between lfc-p-4 lfc-border-b lfc-border-border-subtle lfc-rounded-t-lg"
        style={{ backgroundColor: config.primaryColor ? `${config.primaryColor}10` : undefined }}
      >
        <div className="lfc-flex lfc-items-center lfc-space-x-3">
          <Avatar
            avatarUrl={aiAvatarUrl || config.avatarUrl}
            primaryColor={config.primaryColor}
            altText="AI Assistant"
            fallbackText="AI"
            className="lfc-w-[38px] lfc-h-[38px] lfc-mr-2"
          />
          <div>
              <h3 className="lfc-text-sm lfc-font-semibold lfc-text-text-primary">
                {aiName || config?.showName || t('chat.aiAssistant')}
              </h3>
              <p className="lfc-text-xs lfc-text-text-secondary">
                {isLoading ? t('chat.loading') : t('chat.online')}
              </p>
          </div>
        </div>

        <button
          onClick={onClose}
          className="lfc-text-text-tertiary hover:lfc-text-text-secondary lfc-transition-colors lfc-p-1 lfc-rounded-full hover:lfc-bg-bg-layer"
            aria-label={t('chat.close')}
        >
          <svg className="lfc-w-5 lfc-h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      {/* Error Display */}
      {error && (
        <div className="lfc-px-4 lfc-py-2 lfc-bg-state-danger-bg lfc-border-b lfc-border-state-danger-border">
          <p className="lfc-text-sm lfc-text-state-danger-text">{error}</p>
        </div>
      )}

      {/* Message List */}
      <div className="lfc-flex-1 lfc-overflow-hidden">
        <MessageList
          conversation={conversation}
          config={config}
          isLoading={isLoading}
          onEmailSubmit={onEmailSubmit}
          onWhatsAppClick={onWhatsAppClick}
          aiName={aiName}
          aiAvatarUrl={aiAvatarUrl}
        />
      </div>

      {/* Message Input */}
      <div className="lfc-border-t lfc-border-border-subtle">
        <MessageInput
          onSendMessage={onSendMessage}
          disabled={isLoading}
          config={config}
        />
      </div>
      {/* Free plan badge */}
      {!(typeof window !== 'undefined' && (window as any).linkflowChat?.isPremium) && (
        <div className="lfc-text-[10px] lfc-text-text-tertiary lfc-text-center lfc-py-2 lfc-border-t lfc-border-border-subtle">
          Powered by <a href="https://linkflow.chat" target="_blank" rel="noreferrer" className="lfc-underline">linkflow.chat</a>
        </div>
      )}
    </div>
  )
}

export default ChatWindow