import React, { useState, useEffect, useRef, useCallback } from 'react'
import { BsX } from 'react-icons/bs'

interface Tab {
  id: string
  url: string
  title: string
  isLoading: boolean
  canGoBack: boolean
  canGoForward: boolean
}

const BrowserWindow: React.FC = () => {
  const [tabs, setTabs] = useState<Tab[]>([])
  const [activeTabId, setActiveTabId] = useState<string | null>(null)
  const contentRef = useRef<HTMLDivElement>(null)

  const handleTabCreated = useCallback((_event: unknown, tab: { id: string; url: string; title: string }) => {
    setTabs((prev) => [...prev, { ...tab, isLoading: true, canGoBack: false, canGoForward: false }])
    setActiveTabId(tab.id)
  }, [])

  const handleTabUpdate = useCallback((_event: unknown, id: string, updates: Partial<Tab>) => {
    setTabs((prev) => prev.map((t) => (t.id === id ? { ...t, ...updates } : t)))
  }, [])

  const handleTabsSync = useCallback(
    (_event: unknown, snapshots: Array<{ id: string; url: string; title: string }>) => {
      if (!snapshots?.length) return
      setTabs(
        snapshots.map((s) => ({
          ...s,
          isLoading: true,
          canGoBack: false,
          canGoForward: false
        }))
      )
      setActiveTabId(snapshots[snapshots.length - 1].id)
    },
    []
  )

  // 更新 BrowserView 的位置
  const updateViewBounds = useCallback(() => {
    if (!contentRef.current) return
    const rect = contentRef.current.getBoundingClientRect()
    // 获取窗口的缩放比例（如果需要）
    const zoomFactor = 1 // window.devicePixelRatio
    
    const bounds = {
        x: Math.round(rect.x * zoomFactor),
        y: Math.round(rect.y * zoomFactor),
        width: Math.round(rect.width * zoomFactor),
        height: Math.round(rect.height * zoomFactor)
    }

    if (window.electron && window.electron.ipcRenderer) {
        window.electron.ipcRenderer.send('browser-action', { type: 'resize-view', bounds })
    }
  }, [])

  // 监听来自主进程的事件（先注册再通知主进程，避免首标签 tab-created 丢失）
  useEffect(() => {
    const ipc = window.electron?.ipcRenderer
    if (!ipc) return

    ipc.on('tab-created', handleTabCreated)
    ipc.on('tab-update', handleTabUpdate)
    ipc.on('browser-tabs-sync', handleTabsSync)
    ipc.send('browser-action', { type: 'browser-ui-ready' })

    window.addEventListener('resize', updateViewBounds)
    setTimeout(updateViewBounds, 100)

    return () => {
      ipc.removeListener('tab-created', handleTabCreated)
      ipc.removeListener('tab-update', handleTabUpdate)
      ipc.removeListener('browser-tabs-sync', handleTabsSync)
      window.removeEventListener('resize', updateViewBounds)
    }
  }, [handleTabCreated, handleTabUpdate, handleTabsSync, updateViewBounds])
  
  // 当 tabs 或 activeTabId 变化导致布局变化时，调整 BrowserView 的 bounds
  useEffect(() => {
      updateViewBounds()
  }, [tabs.length, activeTabId, updateViewBounds])

  const handleSwitchTab = (id: string) => {
      setActiveTabId(id)
      window.electron.ipcRenderer.send('browser-action', { type: 'switch-tab', id })
  }

  const closeTab = (e: React.MouseEvent, tabId: string) => {
    e.stopPropagation()
    // 先在前端乐观更新UI，防止闪烁
    const newTabs = tabs.filter(t => t.id !== tabId)
    let newActiveId = activeTabId

    if (activeTabId === tabId) {
        if (newTabs.length > 0) {
            newActiveId = newTabs[newTabs.length - 1].id
            setActiveTabId(newActiveId)
            window.electron.ipcRenderer.send('browser-action', { type: 'switch-tab', id: newActiveId })
        } else {
            setActiveTabId(null)
            window.close() 
        }
    }
    setTabs(newTabs)
    
    // 通知主进程关闭
    window.electron.ipcRenderer.send('browser-action', { type: 'close-tab', id: tabId })
  }


  return (
    <div className="browser-window" style={{ display: 'flex', flexDirection: 'column', height: '100vh', width: '100vw', backgroundColor: '#f5f5f5', overflow: 'hidden' }}>
      {/* Title Bar / Tab Bar */}
      <div className="browser-header" style={{ height: '38px', display: 'flex', alignItems: 'flex-end', backgroundColor: '#e2e2e2', paddingLeft: '80px', WebkitAppRegion: 'drag' } as any}>
        <div style={{ display: 'flex', overflowX: 'auto', height: '100%', alignItems: 'flex-end', WebkitAppRegion: 'no-drag' } as any}>
          {tabs.map(tab => (
            <div
              key={tab.id}
              onClick={() => handleSwitchTab(tab.id)}
              style={{
                padding: '0 8px',
                height: '30px',
                width: '180px',
                backgroundColor: activeTabId === tab.id ? '#ffffff' : 'transparent',
                borderTopLeftRadius: '6px',
                borderTopRightRadius: '6px',
                display: 'flex',
                alignItems: 'center',
                fontSize: '12px',
                cursor: 'default',
                marginRight: '2px',
                position: 'relative',
                userSelect: 'none',
                color: '#333'
              }}
              title={tab.title}
            >
              {tab.isLoading && <div className="spinner" style={{width: 12, height: 12, border: '2px solid #ccc', borderTopColor: '#333', borderRadius: '50%', marginRight: 6, animation: 'spin 1s linear infinite'}}></div>}
              <div style={{ flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', marginRight: '5px' }}>
                {tab.title || 'Loading...'}
              </div>
              <div
                onClick={(e) => closeTab(e, tab.id)}
                style={{ cursor: 'pointer', padding: '2px', borderRadius: '50%', display: 'flex', alignItems: 'center' }}
                className="close-btn"
              >
                <BsX size={14} />
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 导航栏已隐藏：仅保留标签栏与网页内容区 */}

      {/* Content Container (Placeholder for BrowserView) */}
      <div 
        ref={contentRef}
        style={{ flex: 1, position: 'relative', backgroundColor: '#fff' }}
      >
        {tabs.length === 0 && (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', color: '#999', flexDirection: 'column' }}>
            <div style={{ fontSize: '48px', marginBottom: '10px' }}>🌐</div>
            <div>没有打开的标签页</div>
          </div>
        )}
      </div>
      
      <style>{`
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
        .close-btn:hover {
            background-color: #ddd;
        }
      `}</style>
    </div>
  )
}

export default BrowserWindow
