import React, { useEffect, useRef } from 'react';
import { Animated, View, type DimensionValue, type StyleProp, type ViewStyle } from 'react-native';
import { useTheme } from '../../theme';

interface SkeletonProps {
  /** 宽度：数字（dp）或百分比字符串（如 '100%'） */
  width: number | string;
  /** 高度（dp） */
  height: number;
  /** 圆角，默认 theme.radii.sm */
  borderRadius?: number;
  style?: StyleProp<ViewStyle>;
}

/**
 * 骨架屏占位块。
 * 背景取 theme.colors.skeleton，opacity 在 0.3 ~ 1 之间循环闪烁模拟加载呼吸感。
 */
export function Skeleton({ width, height, borderRadius, style }: SkeletonProps) {
  const { theme } = useTheme();
  const opacity = useRef(new Animated.Value(0.3)).current;

  // 闪烁动画：随组件挂载启动、卸载停止，避免泄漏
  useEffect(() => {
    const loop = Animated.loop(
      Animated.sequence([
        Animated.timing(opacity, { toValue: 1, duration: 750, useNativeDriver: true }),
        Animated.timing(opacity, { toValue: 0.3, duration: 750, useNativeDriver: true }),
      ]),
    );
    loop.start();
    return () => loop.stop();
  }, [opacity]);

  return (
    <Animated.View
      accessible={false}
      style={[
        {
          width: width as DimensionValue,
          height,
          borderRadius: borderRadius ?? theme.radii.sm,
          backgroundColor: theme.colors.skeleton,
          opacity,
        },
        style,
      ]}
    />
  );
}

interface SkeletonTextProps {
  /** 行数，默认 3 */
  lines?: number;
  /** 每行高度（dp），默认 14 */
  lineHeight?: number;
  style?: StyleProp<ViewStyle>;
}

/**
 * 多行文字骨架。
 * 末行缩短为 60% 宽，模拟自然段落的参差节奏。
 */
export function SkeletonText({ lines = 3, lineHeight = 14, style }: SkeletonTextProps) {
  const { theme } = useTheme();

  return (
    <View style={style}>
      {Array.from({ length: Math.max(0, lines) }, (_, index) => (
        <Skeleton
          key={index}
          width={index === lines - 1 && lines > 1 ? '60%' : '100%'}
          height={lineHeight}
          style={index > 0 ? { marginTop: theme.spacing.sm } : undefined}
        />
      ))}
    </View>
  );
}
