import React, { useState } from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { AtIcon } from 'taro-ui'
import './index.scss'

interface Props {
  code: string
  language?: string
}

const CodeBlock: React.FC<Props> = ({ code, language }) => {
  const [copied, setCopied] = useState(false)

  const handleCopy = (e) => {
    e.stopPropagation()
    Taro.setClipboardData({
      data: code,
      success: () => {
        setCopied(true)
        setTimeout(() => setCopied(false), 2000)
      }
    })
  }

  return (
    <View className='markdown-code-block'>
      <View className='code-header'>
        <Text className='language'>{language || 'text'}</Text>
        <View className='copy-btn' onClick={handleCopy}>
          <AtIcon value='copy' size='14' color='#ccc' />
          <Text className='copy-text'>{copied ? '已复制' : '复制'}</Text>
        </View>
      </View>
      <ScrollView scrollX scrollY className='code-content'>
        <Text userSelect className='code-text'>{code}</Text>
      </ScrollView>
    </View>
  )
}

export default CodeBlock
