import type { MindElixirInstance } from '../types/index'
import side from '../icons/side.svg?raw'
import left from '../icons/left.svg?raw'
import right from '../icons/right.svg?raw'
import full from '../icons/full.svg?raw'
import living from '../icons/living.svg?raw'
import zoomin from '../icons/zoomin.svg?raw'
import zoomout from '../icons/zoomout.svg?raw'

// 导出按钮的SVG图标 - 调整尺寸与其他图标保持一致
const exportSvgIcon = `<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1750169419447" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2480" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M896 128H128c-35.3 0-64 28.7-64 64v640c0 35.3 28.7 64 64 64h768c35.3 0 64-28.7 64-64V192c0-35.3-28.7-64-64-64zM832 832H192V192h640v640z" p-id="2481"></path><path d="M192 256h640v64H192v-64zM192 384h640v64H192v-64zM192 512h640v64H192v-64zM192 640h448v64H192v-64zM192 768h320v64H192v-64z" p-id="2482"></path></svg>`

import './toolBar.less'

// 导出功能 - 按照官方文档实现
const downloadExport = (type: 'svg') => {
  return async (mind: MindElixirInstance) => {
    try {
      console.log(`🖼️ 开始导出${type.toUpperCase()}文件...`)
      
      // 获取当前思维导图的标题作为文件名
      const title = mind.nodeData?.topic || '思维导图'
      const filename = `${title}_${new Date().toISOString().slice(0, 10)}`
      
      // 完整的CSS样式，包括表格样式
      const style = `
        .topic { font-family: Arial, sans-serif; font-size: 14px; color: #333; }
        .markdown-content { font-size: 12px; line-height: 1.3; }
        
        /* 表格样式 */
        .markdown-table {
          border-collapse: collapse;
          width: 100%;
          margin: 4px 0;
          font-size: 11px;
          border: 1px solid #e0e0e0;
          border-radius: 6px;
          box-shadow: 0 2px 8px rgba(0,0,0,0.08);
          background-color: #fafafa;
          overflow: hidden;
          white-space: normal;
        }
        
        .markdown-table th,
        .markdown-table td {
          border: 1px solid #e0e0e0;
          padding: 8px 12px;
          text-align: left;
          vertical-align: top;
          position: relative;
          white-space: normal;
        }
        
        .markdown-table th {
          background-color: #f5f5f5;
          font-weight: 600;
          color: #333;
          text-align: center;
          border-bottom: 1px solid #d0d0d0;
        }
        
        .markdown-table td {
          background-color: #fff;
        }
        
        .markdown-table tr:nth-child(even) td {
          background-color: #f8f8f8;
        }
        
        .markdown-table tr:hover td {
          background-color: #f0f8ff;
        }
        
        /* 移除多余的边框，保持简洁 */
        .markdown-table th:not(:last-child),
        .markdown-table td:not(:last-child) {
          border-right: 1px solid #e0e0e0;
        }
        
        .markdown-table tr:not(:last-child) td {
          border-bottom: 1px solid #e0e0e0;
        }
      `
      
      const blob = await mind.exportSvg(false, style)
      
      if (!blob) {
        console.error('导出失败：无法生成文件')
        return
      }
      
      // 创建下载链接
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `${filename}.${type}`
      a.click()
      URL.revokeObjectURL(url)
      
      console.log(`✅ 成功导出${type.toUpperCase()}文件: ${filename}.${type}`)
    } catch (e) {
      console.error('导出失败:', e)
      alert(`导出${type.toUpperCase()}失败，请重试`)
    }
  }
}

const map: Record<string, string> = {
  side,
  left,
  right,
  full,
  living,
  zoomin,
  zoomout,
  exportSvg: exportSvgIcon,
}
const createButton = (id: string, name: string) => {
  const button = document.createElement('span')
  button.id = id
  button.innerHTML = map[name]
  return button
}

function createToolBarRBContainer(mind: MindElixirInstance) {
  try {
    console.log('🔧 开始创建右侧工具栏容器...')
    const toolBarRBContainer = document.createElement('div')
    const fc = createButton('fullscreen', 'full')
    const gc = createButton('toCenter', 'living')
    const zo = createButton('zoomout', 'zoomout')
    const zi = createButton('zoomin', 'zoomin')
    
    // 添加导出按钮
    console.log('🔧 开始创建导出按钮...')
    const exportSvg = createButton('exportSvg', 'exportSvg')
  
  console.log('🔧 创建导出按钮:', { exportSvg })
  console.log('🔧 导出按钮内容:', { 
    svgContent: exportSvg.innerHTML 
  })
  
  // 添加工具提示
  exportSvg.title = '导出SVG矢量图'
  
  const percentage = document.createElement('span')
  percentage.innerText = '100%'
  
  toolBarRBContainer.appendChild(fc)
  toolBarRBContainer.appendChild(gc)
  toolBarRBContainer.appendChild(zo)
  toolBarRBContainer.appendChild(zi)
  toolBarRBContainer.appendChild(exportSvg)
  // toolBarRBContainer.appendChild(percentage)
  toolBarRBContainer.className = 'mind-elixir-toolbar rb'
  
  // 调试信息：确认按钮数量
  console.log('🔍 工具栏按钮数量:', toolBarRBContainer.children.length)
  console.log('🔍 工具栏按钮列表:', Array.from(toolBarRBContainer.children).map(child => ({
    id: child.id,
    tagName: child.tagName,
    innerHTML: child.innerHTML.substring(0, 50)
  })))
  fc.onclick = () => {
    if (document.fullscreenElement === mind.el) {
      document.exitFullscreen()
      // 退出全屏后，确保交互正常
      setTimeout(() => {
        mind.el.focus()
        console.log('📱 已退出全屏模式，恢复节点交互')
      }, 100)
    } else {
      mind.el.requestFullscreen()
      // 进入全屏后，优化交互体验
      setTimeout(() => {
        console.log('📱 已进入全屏模式，节点交互可能受限')
      }, 100)
    }
  }
  gc.onclick = () => {
    mind.toCenter()
  }
  zo.onclick = () => {
    mind.scale(mind.scaleVal - mind.scaleSensitivity)
  }
  zi.onclick = () => {
    mind.scale(mind.scaleVal + mind.scaleSensitivity)
  }
  
  // 导出按钮点击事件
  exportSvg.onclick = () => {
    console.log('📄 点击导出SVG按钮')
    downloadExport('svg')(mind)
  }
  
  // 调试信息：确认按钮已创建
  console.log('✅ 导出按钮已创建:', {
    exportSvg: exportSvg,
    container: toolBarRBContainer,
    exportSvgVisible: exportSvg.style.display,
    containerChildren: toolBarRBContainer.children.length
  })
  
  // 延迟检查按钮是否真的在DOM中
  setTimeout(() => {
    const svgButton = document.getElementById('exportSvg')
    console.log('🔍 延迟检查按钮DOM状态:', {
      svgButton: svgButton,
      svgButtonVisible: svgButton ? window.getComputedStyle(svgButton).display : 'not found'
    })
  }, 1000)

  console.log('✅ 右侧工具栏容器创建完成')
  return toolBarRBContainer
  } catch (error) {
    console.error('❌ 创建右侧工具栏容器失败:', error)
    // 返回一个基本的工具栏容器
    const fallbackContainer = document.createElement('div')
    fallbackContainer.className = 'mind-elixir-toolbar rb'
    return fallbackContainer
  }
}
function createToolBarLTContainer(mind: MindElixirInstance) {
  const toolBarLTContainer = document.createElement('div')
  const l = createButton('tbltl', 'left')
  const r = createButton('tbltr', 'right')
  const s = createButton('tblts', 'side')

  toolBarLTContainer.appendChild(l)
  toolBarLTContainer.appendChild(r)
  toolBarLTContainer.appendChild(s)
  toolBarLTContainer.className = 'mind-elixir-toolbar lt'
  l.onclick = () => {
    mind.initLeft()
  }
  r.onclick = () => {
    mind.initRight()
  }
  s.onclick = () => {
    mind.initSide()
  }
  return toolBarLTContainer
}

export default function (mind: MindElixirInstance) {
  try {
    console.log('🔧 工具栏插件开始初始化...')
    console.log('🔧 MindElixir实例:', mind)
    console.log('🔧 容器元素:', mind.container)
    
    if (!mind.container) {
      console.error('❌ 容器元素不存在，无法创建工具栏')
      return
    }
    
    const rbContainer = createToolBarRBContainer(mind)
    const ltContainer = createToolBarLTContainer(mind)
    
    console.log('🔧 右侧工具栏容器:', rbContainer)
    console.log('🔧 左侧工具栏容器:', ltContainer)
    
    mind.container.append(rbContainer)
    mind.container.append(ltContainer)
    
    console.log('✅ 工具栏插件初始化完成，已添加导出按钮')
    console.log('✅ 容器子元素数量:', mind.container.children.length)
  } catch (error) {
    console.error('❌ 工具栏插件初始化失败:', error)
  }
}
