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

interface RibbonItem {
  id: string
  icon: string
  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: '配置'
}

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 st = useStore.getState

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

  const curPage = pages[curIdx]
  const curScreen = curPage?.screen ?? -1
  const carouselRunning = screens.some((s) => s.index === curScreen && /轮播/.test(s.playing?.title ?? ''))

  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: 'open', icon: '📂', label: '打开', 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: '👁️',
      label: '预览本页',
      disabled: !curPage,
      title: '弹窗选择目标屏幕，全屏播放当前页面（Esc 退出 · F5 刷新 · 数字键切页）',
      action: () => setPubModal('preview')
    },
    {
      id: 'single',
      icon: '🎠',
      label: '单屏发布',
      disabled: !curPage,
      title: '弹窗选择目标屏幕，在该屏幕轮播所有「参与多屏发布」的页面（↑/↓ 或数字键切换 · Esc 退出）',
      action: () => setPubModal('single')
    },
    { id: 'multi', icon: '🖥️', label: '多屏发布', type: 'primary', action: () => setPubModal('multi') },
    {
      id: 'stopcar',
      icon: '⏹️',
      label: '停止轮播',
      type: 'danger',
      disabled: !carouselRunning,
      title: carouselRunning ? '停止当前页所属屏幕（屏 ' + curScreen + '）的轮播' : '目标屏幕当前未在轮播',
      action: () => {
        if (curPage) void stopCarouselOnScreen(curPage.screen)
      }
    },
    { 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: props.configMenu === m.id ? ('accent' as const) : undefined,
                action: () => {
                  setView('config')
                  props.onConfigMenu(m.id)
                }
              }))
            )}
            {renderGroup('工具', [
              {
                id: 'shortcut',
                icon: '🖱️',
                label: '桌面快捷方式',
                action: () =>
                  void window.api.createShortcut().then((ok) => toast(ok ? '已创建桌面快捷方式' : '创建快捷方式失败', ok ? 'ok' : 'warn'))
              }
            ])}
          </>
        )}
      </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 === 'multi' && <MultiPublishModal onClose={() => setPubModal(null)} />}
      {pubModal === 'detect' && <DetectModal onClose={() => setPubModal(null)} />}
    </div>
  )
}
