import React, { useState, useEffect, useCallback } from 'react'
import { useTabStore } from './stores/tabStore'
import { flushSaveToDB } from './stores/tabStore'
import { useEditorStore } from './stores/editorStore'
import { useTheme } from './hooks/useTheme'
import { useSettings } from './hooks/useSettings'
import { useSettingsInit } from './hooks/useSettingsInit'
import { useKeyboard } from './hooks/useKeyboard'
import { useUnsavedWarning } from './hooks/useUnsavedWarning'
import { useFileWatch } from './hooks/useFileWatch'
import { useFileOperations } from './hooks/useFileOperations'
import { useDragDrop } from './hooks/useDragDrop'
import { useAutoSave } from './hooks/useAutoSave'
import { useIpcListeners } from './hooks/useIpcListeners'
import { useToast } from './hooks/useToast'
import { useConfirm } from './hooks/useConfirm'
import { useDefaultStatusBarItems } from './hooks/useStatusBarItems'
import { useStatusBarItem } from './hooks/useStatusBarItem'
import { useAutoSaveStore } from './stores/autoSaveStore'
import { toggleAutoSaveExternal } from './hooks/useAutoSave'
import { Toolbar } from './components/Toolbar/Toolbar'
import { TabBar } from './components/TabBar/TabBar'
import { Editor } from './components/Editor/Editor'
import { SourceEditor } from './components/SourceEditor/SourceEditor'
import { Preview } from './components/Preview/Preview'
import { Sidebar } from './components/Sidebar/Sidebar'
import { StatusBar } from './components/StatusBar/StatusBar'
import { WelcomeScreen } from './components/WelcomeScreen/WelcomeScreen'
import { ToastContainer } from './components/Toast/Toast'
import { ModifiedBanner } from './components/ModifiedBanner/ModifiedBanner'
import { DropOverlay } from './components/DropOverlay/DropOverlay'
import { ErrorBoundary } from './components/ErrorBoundary'
import { AboutDialog } from './components/AboutDialog'
import { ConfirmDialog } from './components/ConfirmDialog/ConfirmDialog'

/** 状态栏 — 自动保存开关组件 */
function AutoSaveStatusItem() {
  const activeTab = useTabStore(s => s.getActiveTab())
  const { isAutoSaving, autoSaveEnabled } = useAutoSaveStore()

  if (!activeTab?.filePath) return null

  return (
    <button
      className={`status-auto-save${isAutoSaving ? ' saving' : ''}`}
      title={isAutoSaving ? '正在自动保存...' : (autoSaveEnabled ? '自动保存已开启 — 点击关闭' : '自动保存已关闭 — 点击开启')}
      aria-label={isAutoSaving ? '正在自动保存' : (autoSaveEnabled ? '关闭自动保存' : '开启自动保存')}
      onClick={toggleAutoSaveExternal}
    >
      {isAutoSaving ? '保存中...' : (autoSaveEnabled ? '自动' : '手动')}
    </button>
  )
}

export function App() {
  const tabs = useTabStore(s => s.tabs)
  const activeTabId = useTabStore(s => s.activeTabId)
  const createTab = useTabStore(s => s.createTab)
  const setModified = useTabStore(s => s.setModified)
  const updateTabContent = useTabStore(s => s.updateTabContent)
  const loadFromDB = useTabStore(s => s.loadFromDB)
  const viewMode = useEditorStore(s => s.viewMode)
  const externallyModified = useEditorStore(s => s.externallyModified)
  const setExternallyModified = useEditorStore(s => s.setExternallyModified)
  const { darkMode, toggleDarkMode } = useTheme()
  const { saveViewMode } = useSettings()
  const { toasts, showToast, dismissToast, cleanup } = useToast()
  const { confirm, confirmDialogProps } = useConfirm()
  const [showAbout, setShowAbout] = useState(false)
  const handleCloseAbout = useCallback(() => setShowAbout(false), [])

  useSettingsInit()
  useEffect(() => { loadFromDB(); return cleanup }, [loadFromDB, cleanup])

  const { handleOpenFile, handleSave, handleSaveAs, handleOpenRecent } = useFileOperations(showToast)
  useDragDrop(showToast)
  useFileWatch()
  useAutoSave()

  // UX-01: 传入 confirm 函数替代原生 confirm()
  const handleConfirmClose = useCallback(async (message: string): Promise<boolean> => {
    return confirm({
      title: '未保存的更改',
      message,
      variant: 'warning',
      confirmLabel: '不保存',
      cancelLabel: '取消'
    })
  }, [confirm])

  useUnsavedWarning(() => tabs.some(t => t.isModified), handleConfirmClose, flushSaveToDB)
  useKeyboard(handleOpenFile, handleSave, handleSaveAs)
  useIpcListeners()

  // ── 状态栏扩展点架构 ───────────────────────────────────
  useDefaultStatusBarItems()

  useStatusBarItem({
    id: 'statusbar.auto-save',
    alignment: 'right',
    priority: 200,
    Component: AutoSaveStatusItem
  })

  useEffect(() => {
    if (!window.electronAPI) return
    const activeTab = tabs.find(t => t.id === activeTabId)
    window.electronAPI.tabSwitched(activeTab?.filePath ?? null)
  }, [activeTabId, tabs])

  const handleReloadModified = useCallback(async () => {
    if (!externallyModified?.filePath || !window.electronAPI) return
    const tab = tabs.find(t => t.filePath === externallyModified.filePath)
    // BUG-10: Don't overwrite editor content the user has modified since the last save.
    // The watcher restart after save can trigger a false 'change' event, and re-reading
    // the file at that point would replace newer editor content with the just-saved content.
    if (tab?.isModified) return
    if (!tab) return
    const result = await window.electronAPI.readFile(externallyModified.filePath)
    if (result.success && result.content !== undefined) {
      updateTabContent(tab.id, result.content)
      setModified(tab.id, false)
    }
    setExternallyModified(null)
  }, [externallyModified, tabs, updateTabContent, setModified, setExternallyModified])

  return (
    <ErrorBoundary>
      <div id="app" className={`mode-${viewMode}`}>
        <Toolbar
          onOpen={handleOpenFile} onSave={handleSave}
          viewMode={viewMode} onViewModeChange={saveViewMode}
          darkMode={darkMode} onToggleDark={toggleDarkMode}
          onShowAbout={() => setShowAbout(true)}
        />
        <div id="workspace">
          <Sidebar />
          <div id="main-content">
            <TabBar />
            {externallyModified && (
              <ModifiedBanner onReload={handleReloadModified} onDismiss={() => setExternallyModified(null)} />
            )}
            {tabs.length > 0 ? (
              <div id="content-wrapper">
                {viewMode === 'editor' && <div id="editor-panel"><Editor darkMode={darkMode} /></div>}
                {viewMode === 'source' && <div id="editor-panel"><SourceEditor darkMode={darkMode} /></div>}
                {viewMode === 'preview' && <div id="preview-panel"><Preview /></div>}
              </div>
            ) : (
              <WelcomeScreen onOpen={handleOpenFile} onNew={() => createTab(null, '')} onOpenRecent={handleOpenRecent} />
            )}
          </div>
        </div>
        <StatusBar />
        <ToastContainer toasts={toasts} onDismiss={dismissToast} />
        <DropOverlay />
        {showAbout && <AboutDialog onClose={handleCloseAbout} />}
        <ConfirmDialog {...confirmDialogProps} />
      </div>
    </ErrorBoundary>
  )
}

App.displayName = 'App'
export default App
