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 parseRecursive(child).map((part, index) => (
        <Text key={index} style={[style, part.style]}>
          {part.children}
        </Text>
      ));
    } 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>;
}

interface ParsedPart {
  children: ReactNode;
  style: TextStyle;
}

const parseRecursive = (htmlString: string): ParsedPart[] => {
  const regex = /<(b|i|u|span|br)(?:\s+style=["']color:\s*(.*?)["'])?\s*>(.*?)<\/\1>|<br\s*\/?>/i;
  const match = htmlString.match(regex);

  if (!match) {
    return [{ children: htmlString, style: {} }];
  }

  const parts: ParsedPart[] = [];
  const [fullMatch, tag, color, content] = match;
  const index = match.index!;

  if (index > 0) {
    parts.push({ children: htmlString.substring(0, index), style: {} });
  }
  let currentStyle: TextStyle = {};
  switch (tag?.toLowerCase()) {
    case 'b': currentStyle.fontWeight = 'bold'; break;
    case 'i': currentStyle.fontStyle = 'italic'; break;
    case 'u': currentStyle.textDecorationLine = 'underline'; break;
    case 'span': if (color) currentStyle.color = color.trim(); break;
    case 'br':
      parts.push({ children: '\n', style: {} });
      break;
  }

  if (tag !== 'br' && content !== undefined) {
    const nestedParts = parseRecursive(content).map(p => ({
      ...p,
      style: { ...currentStyle, ...p.style }
    }));
    parts.push(...nestedParts);
  }

  const remaining = htmlString.substring(index + fullMatch.length);
  if (remaining) {
    parts.push(...parseRecursive(remaining));
  }

  return parts;
};
