import React, { useRef } from 'react';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import Tooltip from '@mui/material/Tooltip';
import Button from '@mui/material/Button';
import Divider from '@mui/material/Divider';
import InputBase from '@mui/material/InputBase';
import { useTheme } from '@mui/material/styles';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import ArrowForwardIcon from '@mui/icons-material/ArrowForward';
import RefreshIcon from '@mui/icons-material/Refresh';
import SearchIcon from '@mui/icons-material/Search';
import OpenInNewIcon from '@mui/icons-material/OpenInNew';
import HomeIcon from '@mui/icons-material/Home';
import MenuBar from './MenuBar.jsx';
import PanelIcon from './PanelIcon.jsx';

/* ============================================================
 * Toolbar：VSCode 风格顶栏（高度 56px）
 *
 *  Rain Work(渐变字标) | 菜单栏 | ← → ↻ | 地址栏(自适应填满) | 搜索 | 返回
 * - 地址栏仅展示当前面板 URL（嵌入地址优先），只读、可点开新标签；
 *   flex:1 填满顶栏剩余空间，左侧内容变宽时自然缩减
 * - 搜索框：面板名/URL/分组，Enter 直达（逻辑由 Workbench 注入）
 * ============================================================ */

export default function Toolbar({
  menus = [],
  canBack = false, canForward = false, onBack, onForward, onRefresh,
  currentPanel = null, onOpenExternal,
  search = '', onSearchChange, onSearchEnter,
  searchInputRef = null, onBackHome,
}) {
  const muiTheme = useTheme();
  const searchRef = useRef(null);
  const inputRef = searchInputRef || searchRef;

  const currentUrl = currentPanel ? (currentPanel.embed_url || currentPanel.url || '') : '';
  const logoGradient = `linear-gradient(135deg, ${muiTheme.palette.primary.main} 0%, ${muiTheme.palette.tertiary.main} 100%)`;

  return (
    <Box
      component="header"
      sx={{
        height: 56, flexShrink: 0, display: 'flex', alignItems: 'center',
        gap: 0.5, px: 1, zIndex: 10,
        bgcolor: 'background.paper', borderBottom: 1, borderColor: 'divider',
      }}
    >
      {/* 品牌：纯文字 Logo，MD3 渐变字重 */}
      <Box
        component="span"
        aria-label="Rain Work"
        sx={{
          fontSize: 19.5, fontWeight: 700, letterSpacing: 0.4, mr: 1, flexShrink: 0,
          background: logoGradient, WebkitBackgroundClip: 'text', backgroundClip: 'text',
          WebkitTextFillColor: 'transparent', color: 'transparent',
          userSelect: 'none',
        }}
      >
        Rain Work
      </Box>

      <MenuBar menus={menus} />

      <Divider orientation="vertical" flexItem sx={{ mx: 0.5 }} />

      {/* 导航：后退 / 前进 / 刷新 */}
      <Tooltip title="后退">
        <span><IconButton size="small" onClick={onBack} disabled={!canBack} aria-label="后退"><ArrowBackIcon fontSize="small" /></IconButton></span>
      </Tooltip>
      <Tooltip title="前进">
        <span><IconButton size="small" onClick={onForward} disabled={!canForward} aria-label="前进"><ArrowForwardIcon fontSize="small" /></IconButton></span>
      </Tooltip>
      <Tooltip title="刷新当前面板">
        <span><IconButton size="small" onClick={onRefresh} disabled={!currentPanel} aria-label="刷新"><RefreshIcon fontSize="small" /></IconButton></span>
      </Tooltip>

      {/* 地址栏（只读，flex:1 自适应填满顶栏剩余空间；无 maxWidth 上限，
          左侧菜单/导航变宽时自然缩减，顶栏始终占满） */}
      <Box
        role="textbox"
        aria-label="当前面板地址"
        sx={{
          flex: 1, minWidth: 120, maxWidth: 'none', display: 'flex', alignItems: 'center', gap: 0.75,
          mx: 0.75, height: 34, px: 1.25,
          bgcolor: 'background.default', border: 1, borderColor: 'divider', borderRadius: 1.25,
          '&:focus-within': { borderColor: 'primary.main' },
        }}
      >
        {currentPanel && <PanelIcon url={currentUrl} title={currentPanel.title} size={16} />}
        <InputBase
          readOnly
          fullWidth
          value={currentUrl}
          placeholder="未打开面板"
          inputProps={{ 'aria-label': '当前面板地址', style: { cursor: 'default', fontSize: 12.5 } }}
          sx={{ color: 'text.secondary' }}
        />
        {currentPanel && (
          <Tooltip title="在新标签页打开原站">
            <IconButton size="small" onClick={onOpenExternal} aria-label="在新标签页打开原站">
              <OpenInNewIcon sx={{ fontSize: 16 }} />
            </IconButton>
          </Tooltip>
        )}
      </Box>

      {/* 搜索 */}
      <Box sx={{ position: 'relative', flexShrink: 0 }}>
        <SearchIcon
          sx={{
            position: 'absolute', left: 9, top: '50%', transform: 'translateY(-50%)',
            fontSize: 16, color: 'text.secondary', pointerEvents: 'none',
          }}
        />
        <InputBase
          ref={inputRef}
          value={search}
          onChange={(e) => onSearchChange?.(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter') { onSearchEnter?.(); inputRef.current?.blur(); } }}
          placeholder="搜索面板"
          inputProps={{ 'aria-label': '搜索面板', style: { paddingLeft: 30, fontSize: 12.5 } }}
          sx={{
            height: 34, width: { xs: 100, sm: 150 }, px: 0.5,
            bgcolor: 'background.default', border: 1, borderColor: 'divider',
            borderRadius: 20, '&:focus-within': { borderColor: 'primary.main' },
          }}
        />
      </Box>

      {/* 返回前台 */}
      <Button
        color="inherit"
        onClick={onBackHome}
        startIcon={<HomeIcon sx={{ fontSize: 17 }} />}
        sx={{ ml: 0.5, minWidth: 0, px: { xs: 1, sm: 1.25 }, flexShrink: 0, '& .MuiButton-startIcon': { mr: { xs: 0, sm: 0.5 } } }}
      >
        <Box component="span" sx={{ display: { xs: 'none', sm: 'inline' }, fontSize: 13 }}>返回</Box>
      </Button>
    </Box>
  );
}
