/**
 * PostContentRenderer - 帖子内容渲染器
 * 根据 segments 渲染富文本内容（@提及、投票等）
 * 降级：如果 segments 为空但 content 非空，直接显示纯文本
 */

import React from 'react';
import { View, TouchableOpacity, StyleSheet } from 'react-native';

import Text from '../common/Text';
import { useAppColors } from '../../theme';
import { MessageSegment, AtSegmentData, VoteSegmentData, PostRefSegmentData } from '../../types';
import PostRefCard from './PostRefCard';

interface PostContentRendererProps {
  content?: string;
  segments?: MessageSegment[];
  numberOfLines?: number;
  onMentionPress?: (userId: string) => void;
  onPostRefPress?: (postId: string) => void;
  style?: any;
  textStyle?: any;
}

const PostContentRenderer: React.FC<PostContentRendererProps> = ({
  content,
  segments,
  numberOfLines,
  onMentionPress,
  onPostRefPress,
  style,
  textStyle,
}) => {
  const colors = useAppColors();

  if (!segments || segments.length === 0) {
    return (
      <Text numberOfLines={numberOfLines} selectable style={textStyle}>
        {content || ''}
      </Text>
    );
  }

  const elements: React.ReactNode[] = [];
  let keyIndex = 0;

  for (const segment of segments) {
    const key = `seg_${keyIndex++}`;

    switch (segment.type) {
      case 'text': {
        const text = segment.data?.text || segment.data?.content || '';
        if (text) {
          elements.push(
            <Text key={key} selectable style={textStyle}>
              {text}
            </Text>
          );
        }
        break;
      }

      case 'at': {
        const atData = segment.data as AtSegmentData;
        const userId = atData?.user_id;
        const isAtAll = userId === 'all';
        const displayName = atData?.nickname || (isAtAll ? '所有人' : '某人');
        elements.push(
          <Text
            key={key}
            selectable
            style={[
              textStyle,
              {
                color: colors.primary.main,
                fontWeight: '500',
              },
            ]}
          >
            @{displayName}{' '}
          </Text>
        );
        break;
      }

      case 'vote': {
        const voteData = segment.data as VoteSegmentData;
        if (voteData?.options?.length) {
          elements.push(
            <View key={key} style={[styles.voteBlock, { borderColor: colors.divider }]}>
              <Text style={[styles.voteTitle, { color: colors.text.secondary }]}>
                📊 投票（{voteData.options.length} 个选项）
              </Text>
              {voteData.options.map((opt, i) => (
                <Text key={`vote_opt_${i}`} selectable style={[styles.voteOption, { color: colors.text.primary }]}>
                  {i + 1}. {opt.content}
                </Text>
              ))}
            </View>
          );
        }
        break;
      }

      case 'post_ref': {
        const refData = segment.data as PostRefSegmentData;
        elements.push(
          <PostRefCard
            key={key}
            data={refData}
            compact={!!numberOfLines}
            onPress={onPostRefPress}
          />
        );
        break;
      }

      case 'image':
      case 'link':
      case 'face':
      default:
        break;
    }
  }

  if (elements.length === 0) {
    return (
      <Text numberOfLines={numberOfLines} selectable style={textStyle}>
        {content || ''}
      </Text>
    );
  }

  if (numberOfLines) {
    return (
      <View style={style}>
        <Text numberOfLines={numberOfLines} selectable style={textStyle}>
          {elements}
        </Text>
      </View>
    );
  }

  return <View style={[styles.container, style]}>{elements}</View>;
};

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    alignItems: 'flex-start',
  },
  voteBlock: {
    width: '100%',
    borderWidth: 1,
    borderRadius: 8,
    padding: 10,
    marginTop: 4,
    marginBottom: 4,
  },
  voteTitle: {
    fontSize: 13,
    marginBottom: 6,
  },
  voteOption: {
    fontSize: 14,
    paddingVertical: 2,
  },
});

export default PostContentRenderer;
