import React from 'react'
import { TouchableOpacity } from 'react-native'
import { Svg, SvgXml, SvgProps, Path } from 'react-native-svg'

import svgPaths from './fonts/w-icon.json'

// 定义图标名称类型
export type IconsName = keyof typeof svgPaths

// 图标属性接口
export interface IconsProps extends SvgProps {
    name?: IconsName
    size?: number
    fill?: string
    stroke?: string
    /**
     * SVG path d=`paths`
     */
    paths?: string[]
    /**
     * Svg 图标字符串
     */
    xml?: string
    color?: string
    touchable?: boolean
    onPress?: () => void
}

// 默认导出图标组件
export default function Icon(props: IconsProps) {
    const { size = 26, name, fill = '#000000', stroke, xml, paths, color, touchable = false, onPress, ...otherProps } = props

    // 渲染图标的函数
    const renderIcon = () => {
        if (xml) {
            return <SvgXml testID='RNE__Icon__svgXml' xml={xml} height={size} width={size} {...otherProps} />
        }

        let pathData = paths || (name && svgPaths[name] ? (svgPaths[name] as string[]) : null)

        if (!pathData) {
            return null
        }

        return (
            <Svg testID='RNE__Icon__svg' fill={color || fill} stroke={stroke} height={size} width={size} viewBox='0 0 20 20' {...otherProps}>
                {pathData.map((d: string, i: number) => (
                    <Path key={i} d={d} fillRule='evenodd' />
                ))}
            </Svg>
        )
    }

    // 如果可触摸，返回可触摸的组件
    if (touchable) {
        return <TouchableOpacity onPress={onPress}>{renderIcon()}</TouchableOpacity>
    }

    return renderIcon()
}
