// React not needed for this component
import Empty from '@arcblock/ux/lib/Empty';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { Box, Chip, Link, Stack, Typography } from '@mui/material';

// 定义本地类型，避免依赖问题
type LocalizedText = {
  zh: string;
  en: string;
};

// 简单格式适合大部分业务场景
type SimpleSourceData = Record<string, string>;

// 结构化格式适合复杂场景
type StructuredSourceDataField = {
  key: string;
  label: string | LocalizedText;
  value: string;
  type?: 'text' | 'image' | 'url';
  url?: string;
  group?: string;
};

// 混合类型：支持渐进式接入
type SourceData = SimpleSourceData | StructuredSourceDataField[];

interface SourceDataViewerProps {
  data: SourceData;
  compact?: boolean;
  maxItems?: number;
  locale?: 'en' | 'zh';
  showGroups?: boolean; // 是否显示分组
}

function SourceDataViewer({
  data,
  compact = false,
  maxItems = undefined,
  locale: propLocale = undefined,
  showGroups = false,
}: SourceDataViewerProps) {
  const { locale: contextLocale, t } = useLocaleContext();
  const currentLocale = propLocale || (contextLocale as 'en' | 'zh') || 'en';

  if (
    !data ||
    (Array.isArray(data) && data.length === 0) ||
    (typeof data === 'object' && Object.keys(data).length === 0)
  ) {
    return <Empty>{t('common.none')}</Empty>;
  }

  const getLocalizedText = (text: string | LocalizedText): string => {
    if (typeof text === 'string') {
      return text;
    }
    return text[currentLocale] || text.en || '';
  };

  /**
   * Type guards
   */
  const isSimpleSourceData = (sourceData: SourceData): sourceData is SimpleSourceData => {
    return typeof sourceData === 'object' && !Array.isArray(sourceData) && sourceData !== null;
  };

  /**
   * Auto detect URL pattern
   */
  const isUrlLike = (str: string): boolean => {
    try {
      // eslint-disable-next-line no-new
      new URL(str);
      return true;
    } catch {
      return /^https?:\/\/.+/.test(str) || /^www\..+/.test(str);
    }
  };

  /**
   * Convert any format to normalized structured format with auto URL detection
   */
  const normalizeData = (inputData: SourceData): StructuredSourceDataField[] => {
    if (isSimpleSourceData(inputData)) {
      return Object.entries(inputData).map(([key, value]) => {
        const stringValue = String(value);
        const isUrl = isUrlLike(stringValue);
        return {
          key,
          label: key.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase()),
          value: stringValue,
          type: isUrl ? ('url' as const) : ('text' as const),
          url: isUrl ? stringValue : undefined,
        };
      });
    }
    return inputData;
  };

  /**
   * Render field value based on type
   */
  const renderFieldValue = (field: StructuredSourceDataField) => {
    const displayValue = field.value;

    if (field.type === 'url') {
      return (
        <Link
          href={field.url || field.value}
          target="_blank"
          rel="noopener noreferrer"
          sx={{
            color: 'primary.main',
            textDecoration: 'none',
            fontSize: '0.85rem',
            fontWeight: 600,
            lineHeight: 1.4,
            '&:hover': {
              textDecoration: 'underline',
              color: 'primary.dark',
            },
            '&:visited': {
              color: 'primary.main',
            },
          }}>
          {displayValue}
        </Link>
      );
    }

    if (field.type === 'image') {
      return (
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            gap: 1,
          }}>
          <Box
            component="img"
            src={field.url || field.value}
            alt={displayValue}
            sx={{
              width: 24,
              height: 24,
              borderRadius: 1,
              objectFit: 'cover',
            }}
          />
          <Typography variant="body2" sx={{ fontWeight: 500 }}>
            {displayValue}
          </Typography>
        </Box>
      );
    }

    return (
      <Typography
        variant="body2"
        sx={{
          fontWeight: 500,
          color: 'text.primary',
        }}>
        {displayValue}
      </Typography>
    );
  };

  if (
    !data ||
    (Array.isArray(data) && data.length === 0) ||
    (typeof data === 'object' && Object.keys(data).length === 0)
  ) {
    return null;
  }

  const normalizedData = normalizeData(data);
  const displayItems = maxItems ? normalizedData.slice(0, maxItems) : normalizedData;

  if (compact) {
    return (
      <Stack
        direction="row"
        spacing={1}
        useFlexGap
        sx={{
          flexWrap: 'wrap',
        }}>
        {displayItems.map((field) => (
          <Chip
            key={field.key}
            label={`${getLocalizedText(field.label)}: ${field.value}`}
            size="small"
            variant="outlined"
            sx={{ maxWidth: 200 }}
          />
        ))}
        {maxItems && normalizedData.length > maxItems && (
          <Chip label={`+${normalizedData.length - maxItems} more`} size="small" color="primary" variant="outlined" />
        )}
      </Stack>
    );
  }

  if (showGroups) {
    // Group by group field
    const groupedData = displayItems.reduce(
      (acc, field) => {
        const group = field.group || 'default';
        if (!acc[group]) acc[group] = [];
        acc[group].push(field);
        return acc;
      },
      {} as Record<string, StructuredSourceDataField[]>
    );

    return (
      <Stack spacing={2.5}>
        {Object.entries(groupedData).map(([group, fields]) => (
          <Box key={group}>
            {group !== 'default' && (
              <Typography
                variant="subtitle2"
                sx={{
                  mb: 1.5,
                  fontWeight: 700,
                  color: 'text.primary',
                  letterSpacing: '0.5px',
                  borderBottom: '1px solid',
                  borderColor: 'divider',
                  pb: 0.5,
                }}>
                {group.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase())}
              </Typography>
            )}
            <Stack spacing={1.2} sx={{ pl: group !== 'default' ? 1 : 0 }}>
              {fields.map((field) => (
                <Box
                  key={field.key}
                  sx={{
                    display: 'flex',
                    flexDirection: 'row',
                    alignItems: 'flex-start',
                    gap: 3,
                    minHeight: 20,
                  }}>
                  <Typography
                    variant="body2"
                    sx={{
                      color: 'text.secondary',
                      fontSize: '0.8rem',
                      minWidth: 100,
                      fontWeight: 600,
                      lineHeight: 1.4,
                    }}>
                    {getLocalizedText(field.label)}
                  </Typography>
                  <Box sx={{ flex: 1, minWidth: 0, wordBreak: 'break-all', whiteSpace: 'wrap' }}>
                    {renderFieldValue(field)}
                  </Box>
                </Box>
              ))}
            </Stack>
          </Box>
        ))}
      </Stack>
    );
  }

  return (
    <Stack spacing={1.5}>
      {displayItems.map((field) => (
        <Box
          key={field.key}
          sx={{
            display: 'flex',
            flexDirection: 'row',
            alignItems: 'flex-start',
            gap: 3,
            minHeight: 20,
          }}>
          <Typography
            variant="body2"
            sx={{
              color: 'text.secondary',
              fontSize: '0.8rem',
              minWidth: 100,
              fontWeight: 600,
              lineHeight: 1.4,
            }}>
            {getLocalizedText(field.label)}
          </Typography>
          <Box sx={{ flex: 1, minWidth: 0 }}>{renderFieldValue(field)}</Box>
        </Box>
      ))}
    </Stack>
  );
}

export default SourceDataViewer;
