import { useState, useMemo } from 'react'
import { Modal, message, Row, Col, Card, Tabs, Input } from 'antd'
import { SlateTransforms } from '@wangeditor/editor'
import * as AntIcons from '@ant-design/icons'
import './IconModal.less'

const { Search } = Input

export default function IconModal(props) {
  const { editor } = props
  const [isModalOpen, setIsModalOpen] = useState(true)
  const [selectedIcon, setSelectedIcon] = useState(null)
  const [activeTab, setActiveTab] = useState('image')
  const [searchText, setSearchText] = useState('')

  // 精美图标 (JPG)
  const imageIcons = Array.from({ length: 11 }, (_, i) => ({
    id: i + 1,
    url: `https://webapp-pub.ezijing.com/book-app/icons/${i + 1}.png`,
    type: 'image'
  }))

  // 通用图标 (Ant Design Icons)
  const antIconNames = useMemo(() => {
    return Object.keys(AntIcons).filter(name => 
      name.endsWith('Outlined') && 
      /^[A-Z]/.test(name) &&
      (typeof AntIcons[name] === 'object' || typeof AntIcons[name] === 'function')
    )
  }, [])

  const filteredAntIcons = useMemo(() => {
    let list = antIconNames
    if (searchText) {
      list = antIconNames.filter(name => 
        name.toLowerCase().includes(searchText.toLowerCase())
      )
    }
    return list.slice(0, 120)
  }, [antIconNames, searchText])

  // 选择图标时的处理：如果是 Ant 图标，提前生成 Data URL
  const onSelect = (icon) => {
    if (icon.type === 'ant') {
      const iconElement = document.getElementById(`temp-icon-${icon.name}`)
      if (iconElement) {
        const svgElement = iconElement.querySelector('svg')
        if (svgElement) {
          const clonedSvg = svgElement.cloneNode(true)
          clonedSvg.setAttribute('width', '32')
          clonedSvg.setAttribute('height', '32')
          clonedSvg.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
          // 确保图标有颜色
          if (!clonedSvg.getAttribute('fill') || clonedSvg.getAttribute('fill') === 'currentColor') {
            clonedSvg.setAttribute('fill', '#333333')
          }
          const svgString = new XMLSerializer().serializeToString(clonedSvg)
          try {
            const base64 = btoa(unescape(encodeURIComponent(svgString)))
            setSelectedIcon({ ...icon, url: `data:image/svg+xml;base64,${base64}` })
          } catch (e) {
            setSelectedIcon({ ...icon, url: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgString)}` })
          }
          return
        }
      }
    }
    setSelectedIcon(icon)
  }

  const handleInsert = () => {
    if (!selectedIcon || !selectedIcon.url) {
      message.warning('请先选择一个图标')
      return
    }

    if (editor) {
      editor.restoreSelection()
      
      const iconNode = {
        type: 'image',
        src: selectedIcon.url,
        alt: 'icon-inline',
        style: { width: '32px', height: '32px', verticalAlign: 'middle' },
        width: '32', // 双重保障，部分渲染器读这个
        height: '32',
        children: [{ text: '' }],
      }

      // 很多时候直接插入 image node 可能会被某些编辑器逻辑过滤
      // 我们尝试按照 AIImage 的习惯，如果是在段落里就直接插，否则尝试外层包一下
      SlateTransforms.insertNodes(editor, iconNode)
      
      message.success('图标已插入编辑器！')
      setIsModalOpen(false)
    } else {
      message.error('编辑器未找到')
    }
  }

  const renderImageIcons = () => (
    <Row gutter={[16, 16]}>
      {imageIcons.map((icon) => (
        <Col span={6} key={icon.id}>
          <Card
            hoverable
            className={`icon-item-card ${selectedIcon?.url === icon.url ? 'selected' : ''}`}
            cover={
              <div className="icon-container">
                <img src={icon.url} alt={`icon-${icon.id}`} />
              </div>
            }
            onClick={() => onSelect(icon)}
          />
        </Col>
      ))}
    </Row>
  )

  const renderAntIcons = () => (
    <div className="ant-icons-tab">
      <Search
        placeholder="搜索通用图标"
        allowClear
        onChange={e => setSearchText(e.target.value)}
        style={{ marginBottom: 16 }}
      />
      <div className="ant-icons-grid">
        <Row gutter={[8, 8]}>
          {filteredAntIcons.map((name) => {
            const IconComp = AntIcons[name]
            if (!IconComp) return null
            return (
              <Col span={4} key={name}>
                <div 
                  className={`ant-icon-item ${selectedIcon?.name === name ? 'selected' : ''}`}
                  onClick={() => onSelect({ name, type: 'ant' })}
                >
                  <div id={`temp-icon-${name}`} className="icon-wrapper">
                    <IconComp style={{ fontSize: 24 }} />
                  </div>
                  <div className="ant-icon-name">{name.replace('Outlined', '')}</div>
                </div>
              </Col>
            )
          })}
        </Row>
      </div>
    </div>
  )

  return (
    <Modal
      title="选择图标"
      open={isModalOpen}
      onOk={handleInsert}
      onCancel={() => setIsModalOpen(false)}
      okText="插入"
      cancelText="取消"
      width={700}
      centered
      destroyOnClose
    >
      <Tabs 
        activeKey={activeTab} 
        onChange={setActiveTab}
        items={[
          {
            key: 'image',
            label: '精美图标',
            children: <div className="icon-selection-grid">{renderImageIcons()}</div>
          },
          {
            key: 'ant',
            label: '通用图标',
            children: <div className="ant-icons-container">{renderAntIcons()}</div>
          }
        ]}
      />
    </Modal>
  )
}
