import { useState } from 'react'
import { useStore } from '../store'
import type { ViewMode } from '../types'
import { CONFIG_MENUS, type ConfigMenu } from '../configMenus'
import { closeAllScreenOutput, publishCurrentToScreen, startCarouselOnScreen, stopCarouselAutoOnScreen } from '../publishActions'
import { ScreenSelectModal, MultiPublishModal, InteractiveModal, DetectModal } from './PublishModals'

interface RibbonItem {
  id: string
  icon: string | React.JSX.Element
  label: string
  title?: string
  action?: () => void
  type?: 'primary' | 'accent' | 'danger'
  disabled?: boolean
}

const TAB_ICON: Record<ViewMode, string> = {
  edit: '🖋️',
  config: '⚙️'
}

const TAB_NAME: Record<ViewMode, string> = {
  edit: '编辑',
  config: '配置'
}

/** 发布组按钮统一样式的线性图标（显示器族，currentColor 着色） */
const svgIconProps = {
  width: 15,
  height: 15,
  viewBox: '0 0 24 24',
  fill: 'none',
  stroke: 'currentColor',
  strokeWidth: 1.8,
  strokeLinecap: 'round' as const,
  strokeLinejoin: 'round' as const,
  'aria-hidden': true
}

// 预览本页：显示器 + 播放三角
const PreviewIcon = () => (
  <svg {...svgIconProps}>
    <rect x="3.5" y="4" width="17" height="11.5" rx="2" />
    <path d="M12 15.5V19M8.5 19h7" />
    <path d="M10 8.4l4.7 2.6-4.7 2.6z" fill="currentColor" stroke="none" />
  </svg>
)

// 单屏发布：显示器 + 轮播旋转箭头
const SingleIcon = () => (
  <svg {...svgIconProps}>
    <rect x="4" y="5" width="16" height="11" rx="2" />
    <path d="M12 16v3M8.5 19h7" />
    <path d="M9.5 12a4.5 4.5 0 0 1 7.3-3.6" />
    <path d="M16.5 5.5v3.4h-3.4" />
  </svg>
)

// 多屏发布：两台显示器
const MultiIcon = () => (
  <svg {...svgIconProps}>
    <rect x="3" y="4.5" width="9.5" height="8" rx="1.5" />
    <path d="M7.8 12.5V15M5.2 15h5" />
    <rect x="13.5" y="8" width="8" height="10" rx="1.5" />
    <path d="M17.5 18v2M15 20h5" />
  </svg>
)

// 交互发布：显示器 + 双向切换箭头
const InteractiveIcon = () => (
  <svg {...svgIconProps}>
    <rect x="4" y="5" width="16" height="11" rx="2" />
    <path d="M12 16v3M8.5 19h7" />
    <path d="M8 10.5h8M13.5 8l2.5 2.5-2.5 2.5" />
    <path d="M16 13.5H8M10.5 12 8 14.5l2.5 2.5" />
  </svg>
)

export default function Ribbon(props: {
  configMenu: ConfigMenu
  onConfigMenu: (m: ConfigMenu) => void
}): React.JSX.Element {
  const view = useStore((s) => s.view)
  const setView = useStore((s) => s.setView)
  const pages = useStore((s) => s.pages)
  const curIdx = useStore((s) => s.curIdx)
  const screens = useStore((s) => s.screens)
  const opening = useStore((s) => s.opening)

  const st = useStore.getState

  const [pubModal, setPubModal] = useState<'multi' | 'preview' | 'single' | 'interactive' | 'detect' | null>(null)

  const curPage = pages[curIdx]
  const curScreen = curPage?.screen ?? -1
  const carouseling = screens.filter((s) => s.carouselAuto && /轮播/.test(s.playing?.title ?? ''))
  const carouselRunning = carouseling.length > 0
  // 优先停止当前页所属屏幕的轮播；若该屏未在轮播，则停止第一个正在轮播的屏幕
  const stopTarget = carouseling.find((s) => s.index === curScreen) ?? carouseling[0]

  const editItems: RibbonItem[] = [
    { id: 'add', icon: '📄', label: '新建页面', action: () => st().addPage() },
    { id: 'before', icon: '⏫', label: '插入页面', action: () => st().insertBefore() },
    { id: 'dup', icon: '📑', label: '复制页面', action: () => st().dupPage() },
    { id: 'del', icon: '🗑️', label: '删除页面', type: 'danger', disabled: pages.length <= 1, action: () => st().delPage() },
    { id: 'up', icon: '⬆️', label: '上移', action: () => st().movePage(-1) },
    { id: 'down', icon: '⬇️', label: '下移', action: () => st().movePage(1) },
    { id: 'snap', icon: '📷', label: '缩略图', action: () => void st().capturePreview() }
  ]
  const fileItems: RibbonItem[] = [
    {
      id: 'new',
      icon: '🆕',
      label: '新建',
      title: '创建新的空白工程（默认包含 1 个空白页面，保存时选择位置）',
      action: () => st().newProject()
    },
    {
      id: 'open',
      icon: opening ? '⏳' : '📂',
      label: opening ? '打开中…' : '打开',
      disabled: opening,
      title: opening ? '正在选择并加载工程文件，请稍候…' : '打开工程文件',
      action: () => void st().open()
    },
    { id: 'save', icon: '💾', label: '保存', action: () => void st().save() },
    { id: 'saveas', icon: '📝', label: '另存为', action: () => void st().saveAs() },
    { id: 'resetorder', icon: '🔀', label: '页面重排', action: () => st().resetOrder() }
  ]
  const pubItems: RibbonItem[] = [
    {
      id: 'preview',
      icon: <PreviewIcon />,
      label: '预览本页',
      disabled: !curPage,
      title: '弹窗选择目标屏幕，全屏播放当前页面（Esc 关闭所有 · F5 刷新 · 数字键切页）',
      action: () => setPubModal('preview')
    },
    {
      id: 'single',
      icon: <SingleIcon />,
      label: '单屏发布',
      disabled: !curPage,
      title: '弹窗选择目标屏幕，在该屏幕轮播所有「参与多屏发布」的页面（↑/↓ 或数字键切换 · Esc 退出）',
      action: () => setPubModal('single')
    },
    { id: 'multi', icon: <MultiIcon />, label: '多屏发布', type: 'primary', action: () => setPubModal('multi') },
    {
      id: 'interactive',
      icon: <InteractiveIcon />,
      label: '交互发布',
      type: 'primary',
      title: '指定一块屏幕为交互主屏（大屏），各小屏自行加载本屏页面；在主屏按 ↑/↓ 或数字键轮流展示各屏内容',
      action: () => setPubModal('interactive')
    },
    {
      id: 'stopcar',
      icon: '⏹️',
      label: '停止轮播',
      type: 'danger',
      disabled: !carouselRunning,
      title:
        carouselRunning && stopTarget
          ? `停止屏 ${stopTarget.index} 的自动轮播（保留当前页面窗体，可手动切换）`
          : '仅「自动轮播」模式可用',
      action: () => {
        if (stopTarget) void stopCarouselAutoOnScreen(stopTarget.index)
      }
    },
    { id: 'closeall', icon: '🏁', label: '关闭所有', type: 'danger', action: () => void closeAllScreenOutput() },
    { id: 'detect', icon: '📡', label: '检测屏幕', action: () => setPubModal('detect') }
  ]

  const renderGroup = (label: string, items: RibbonItem[]): React.JSX.Element => (
    <div className="ribbon-group">
      <span className="rg-label">{label}</span>
      {items.map((it) => (
        <button
          key={it.id}
          className={'ribbon-btn' + (it.type ? ' ' + it.type : '')}
          title={it.title ?? it.label}
          disabled={it.disabled}
          onClick={it.action}
        >
          <span className="rb-icon">{it.icon}</span>
          <span>{it.label}</span>
        </button>
      ))}
    </div>
  )

  return (
    <div className="ribbon">
      <div className="ribbon-tabs">
        {(Object.keys(TAB_ICON) as ViewMode[]).map((v) => (
          <button
            key={v}
            className={'ribbon-tab' + (view === v ? ' active' : '')}
            onClick={() => setView(v)}
          >
            <span className="rt-icon">{TAB_ICON[v]}</span>
            {TAB_NAME[v]}
          </button>
        ))}
      </div>
      <div className="ribbon-body">
        {view === 'edit' && (
          <>
            {renderGroup('项目', fileItems)}
            {renderGroup('页面', editItems)}
            {renderGroup('发布', pubItems)}
          </>
        )}
        {view === 'config' && (
          <>
            {renderGroup(
              '配置',
              CONFIG_MENUS.map((m) => ({
                id: m.id,
                icon: m.icon,
                label: m.label,
                title: m.desc,
                type: !m.href && props.configMenu === m.id ? ('accent' as const) : undefined,
                action: () => {
                  if (m.href) {
                    void window.api.shell.openExternal(m.href)
                    return
                  }
                  setView('config')
                  props.onConfigMenu(m.id)
                }
              }))
            )}
          </>
        )}
      </div>
      {pubModal === 'preview' && (
        <ScreenSelectModal
          title="预览本页"
          hint="选择要在哪块屏幕上全屏播放当前页面（Esc 关闭所有 · F5 刷新 · 数字键切页）。"
          confirmLabel="开始预览"
          onConfirm={(i) => {
            void publishCurrentToScreen(i)
            setPubModal(null)
          }}
          onClose={() => setPubModal(null)}
        />
      )}
      {pubModal === 'single' && (
        <ScreenSelectModal
          title="单屏发布"
          hint="选择要在哪块屏幕上轮播所有「参与多屏发布」的页面（↑/↓ 或数字键切换 · Esc 关闭所有 · F5 刷新）。"
          confirmLabel="开始发布"
          showCarousel
          onConfirm={(i, opts) => {
            void startCarouselOnScreen(i, opts.carousel ? opts.intervalSec : 0)
            setPubModal(null)
          }}
          onClose={() => setPubModal(null)}
        />
      )}
      {pubModal === 'interactive' && <InteractiveModal onClose={() => setPubModal(null)} />}
      {pubModal === 'multi' && <MultiPublishModal onClose={() => setPubModal(null)} />}
      {pubModal === 'detect' && <DetectModal onClose={() => setPubModal(null)} />}
    </div>
  )
}
