/* eslint-disable jsx-a11y/anchor-is-valid */
import React, { useState, useEffect, useRef } from 'react'
import styles from './index.module.scss'
import { myData } from '@/utils/http'
import { Tooltip } from 'antd'
import history, { isMobiileFu } from '@/utils/history'

function ModalTxt() {
  const [selectedTab, setSelectedTab] = useState(0)
  const [isOpenMzm, setIsOpenMzm] = useState(false)
  const [modalTxtIndex, setModalTxtIndex] = useState(1)
  const [activeAId, setActiveAId] = useState<number | null>(null)
  const [showTooltip, setShowTooltip] = useState(-1)

  // 备份
  //   #root .ant-tooltip .tooltip_MT {
  //   height: 100%;
  //   font-size: 16px;
  //   line-height: 24px;
  //   color: #000;
  //   display: flex;
  //   flex-direction: column;
  //   padding-bottom: 8px;
  //   gap: 4px;
  //   .top {
  //     width: 100%;
  //     height: 15px;
  //     display: flex;
  //     justify-content: space-between;
  //     align-items: center;
  //     .title {
  //       width: 30px;
  //       height: 100%;
  //       font-size: 10px;
  //       line-height: 15px;
  //       color: rgba(255, 233, 182, 1);
  //     }
  //     .close {
  //       width: 40px;
  //       height: 100%;
  //       cursor: pointer;
  //       display: flex;
  //       justify-content: end;
  //       align-items: center;
  //       & > img {
  //         height: 90%;
  //         object-fit: contain;
  //       }
  //     }
  //   }
  //   .content {
  //     width: 100%;
  //     height: calc(100% - 16px);
  //     font-size: 7px;
  //     line-height: 10px;
  //     color: #fff;
  //     font-weight: lighter;
  //     overflow: auto;
  //     &::-webkit-scrollbar {
  //       width: 1px;
  //     }
  //     &::-webkit-scrollbar-thumb {
  //       background: rgba(255, 233, 182, 1);
  //     }
  //   }
  // }

  // 动态变化zIndex
  useEffect(() => {
    setModalTxtIndex(selectedTab === 0 ? 1 : 2)
    if (isOpenMzm) setModalTxtIndex(10)
  }, [selectedTab, isOpenMzm])

  //动态加入a标签
  const CommentLink = ({ index, word, define }: { index: number; word: string; define: string }) => {
    const handleClick = () => {
      setActiveAId(index)
      setShowTooltip(index)
    }
    return (
      <Tooltip
        title={
          <div className='tooltip_MT'>
            <div className='top'>
              <div className='title'>{word}</div>
              <div className='close' onClick={() => setShowTooltip(-1)} onTouchEnd={() => setShowTooltip(-1)}>
                <img src={require('@/assets/img/close.png')} alt='' draggable='false' />
              </div>
            </div>
            <div className="content">{define}</div>
          </div>
        }
        getPopupContainer={() => document.body.querySelector('#root') as HTMLElement}
        open={showTooltip === index}
        trigger='click'
        placement='topLeft'
        align={{ offset: [-30, 0] }}
        arrow={false}
      >
        <a key={index} className={activeAId === index ? 'active' : ''} onTouchEnd={handleClick} onClick={handleClick} >
          {word}
        </a>
      </Tooltip>
    )
  }

  const CommentText = ({ str, index }: { str: string; index: number }) => {
    // 词
    const convertArr = myData.comment[index].words.map(item => item.name)
    // 解释
    const defineArr = myData.comment[index].words.map(item => item.define)
    const parts = []
    let remainingStr = str

    convertArr.forEach((word, idx) => {
      const regex = new RegExp(word)
      const match = remainingStr.match(regex)

      if (match) {
        const matchIndex = match.index || 0

        // 添加匹配前的文本
        if (matchIndex > 0) {
          parts.push(remainingStr.substring(0, matchIndex))
        }

        // 添加链接组件
        parts.push(<CommentLink key={idx} index={idx} word={word} define={defineArr[idx]} />)

        // 更新剩余字符串
        remainingStr = remainingStr.substring(matchIndex + word.length)
      }
    })

    // 添加剩余的文本
    if (remainingStr) {
      parts.push(remainingStr)
    }

    return <>{parts}</>
  }

  return (
    <div className={styles.modalTxt} id='modalTxt' style={{ zIndex: modalTxtIndex }}>
      <div className='modalTxtContainner'>
        {/* 墓志铭体制之变例 */}
        {selectedTab !== 0 && (
          <div className='extra' onClick={() => setIsOpenMzm(true)}>
            <div className='icon'>
              <img src={require('@/assets/img/tip.png')} alt='' />
            </div>
            <div className='txt'>墓志铭体制之变例</div>
          </div>
        )}

        {isOpenMzm && (
          <div className='mzm'>
            <div className='top'>
              <div className='title'>墓志铭体制之变例</div>
              <div className='close' onClick={() => setIsOpenMzm(false)}>
                <img
                  src={require('@/assets/img/closeWithTxt.png')}
                  alt=''
                  onClick={() => setIsOpenMzm(false)}
                />
              </div>
            </div>
            <div
              className='content'
              dangerouslySetInnerHTML={{ __html: myData.mzmtz.content }}
            ></div>
          </div>
        )}

        <div className='topBar'>
          <div className='beie'>
            <img src={require('@/assets/img/beie.png')} alt='' />
            <div className='txt' onClick={() => history.push('/beie')}>
              碑额
            </div>
          </div>
          <div className='tab ' onClick={() => setSelectedTab(1)}>
            <img
              src={require(`@/assets/img/btn_ModalTxt_bg${selectedTab === 1 ? '_ac' : ''}.png`)}
              alt=''
            />
            <div
              className='txt'
              style={{ display: selectedTab === 1 || selectedTab === 0 ? 'block' : 'none' }}
            >
              造碑人与碑主
            </div>
          </div>
          <div className='tab ' onClick={() => setSelectedTab(2)}>
            <img
              src={require(`@/assets/img/btn_ModalTxt_bg${selectedTab === 2 ? '_ac' : ''}.png`)}
              alt=''
            />
            <div
              className='txt'
              style={{ display: selectedTab === 2 || selectedTab === 0 ? 'block' : 'none' }}
            >
              程哲生平与家族世系
            </div>
          </div>
          <div className='tab ' onClick={() => setSelectedTab(3)}>
            <img
              src={require(`@/assets/img/btn_ModalTxt_bg${selectedTab === 3 ? '_ac' : ''}.png`)}
              alt=''
            />
            <div
              className='txt'
              style={{ display: selectedTab === 3 || selectedTab === 0 ? 'block' : 'none' }}
            >
              颂文
            </div>
          </div>
        </div>

        <div className='intro' style={{ opacity: selectedTab !== 0 ? '1' : '0' }}>
          第一部分列造碑人与碑主。列六位造碑人（程定宗、程文静、程海珍程盖世、程进、程庆仲等）和四位碑主（程钵、程蠡、程买、程哲）。
        </div>

        {selectedTab !== 0 && (
          <div className='detailTxt'>
            <div className='left'>
              <div className='title'>原文</div>
              <div className='txt'>
                {CommentText({
                  str: myData.comment[selectedTab - 1].origin,
                  index: selectedTab - 1
                })}
              </div>
            </div>
            <div className='right'>
              <div className='title'>译文</div>
              <div className='txt'>{myData.comment[selectedTab - 1].translate}</div>
            </div>
          </div>
        )}

        {selectedTab === 0 && (
          <div className='content'>
            <div className='title'>碑文概述</div>
            <div className='text'>
              程哲碑碑文，
              <br /> 31行楷书，满行45字，
              <br /> 字径约2厘米，带方界格，总计1404字；
              <br /> 未刻正式碑名。 <br />
              通篇颂德程氏家族的历史功绩。
            </div>
          </div>
        )}
      </div>
    </div>
  )
}

const MemoModalTxt = React.memo(ModalTxt)

export default MemoModalTxt
