import React, { ReactNode } from 'react';
import { Text, TextProps, TextStyle } from 'react-native';

export interface EventHtmltextProps extends TextProps {
  style?: TextStyle;
  children?: ReactNode;
}

export default function m({ style, children, ...props }: EventHtmltextProps): JSX.Element {
  const renderChildren = (child: ReactNode) => {
    if (typeof child === 'string') {
      return parseHtmlText(child).map((part, index) => (
        <Text key={index} style={[style, part.style]}>
          {part.text}
        </Text>
      ));
    } else if (React.isValidElement(child)) {
      return React.cloneElement(child, {
        style: [style, child.props.style], // Merge styles properly
      });
    } else if (Array.isArray(child)) {
      return child.map((nestedChild, index) => (
        <React.Fragment key={index}>{renderChildren(nestedChild)}</React.Fragment>
      ));
    }
    return child;
  };

  return <Text {...props}>{renderChildren(children)}</Text>;
}

const parseHtmlText = (htmlString: string) => {
  const regex = /(<b>(.*?)<\/b>)|(<i>(.*?)<\/i>)|(<u>(.*?)<\/u>)|(<br\s*\/?>)/g;
  let parts = [];
  let lastIndex = 0;

  htmlString.replace(regex, (match, bold, boldText, italic, italicText, underline, underlineText, br, index) => {
    if (index > lastIndex) {
      parts.push({ text: htmlString.substring(lastIndex, index), style: {} });
    }

    if (boldText) {
      parts.push({ text: boldText, style: { fontWeight: 'bold' } });
    } else if (italicText) {
      parts.push({ text: italicText, style: { fontStyle: 'italic' } });
    } else if (underlineText) {
      parts.push({ text: underlineText, style: { textDecorationLine: 'underline' } });
    } else if (br) {
      parts.push({ text: '\n', style: {} });
    }

    lastIndex = index + match.length;
    return match;
  });

  if (lastIndex < htmlString.length) {
    parts.push({ text: htmlString.substring(lastIndex), style: {} });
  }

  return parts;
};
