import React, { useMemo } from 'react';
import { View, processColor } from 'react-native';
import LottieView from 'lottie-react-native';
import spinnerJson from '@/assets/animations/spinner.json';

// 将任意 RN 颜色字符串转换为 [0-1] 小数的 RGB
function getRgbFractions(inputColor) {
  const intColor = processColor(inputColor);
  if (intColor == null) return null;
  // ARGB => 0xAARRGGBB
  const r = (intColor >> 16) & 255;
  const g = (intColor >> 8) & 255;
  const b = intColor & 255;
  return { r: r / 255, g: g / 255, b: b / 255 };
}

// 深度遍历动画 JSON，将所有纯色/渐变 Fill/Stroke 的颜色改为指定颜色
function colorizeLottieJson(json, color) {
  const rgb = getRgbFractions(color);
  if (!rgb) return json;
  const clone = JSON.parse(JSON.stringify(json));

  const overrideSolid = (node) => {
    // 处理形状颜色：node.c?.k 形如 [r,g,b] 或 [r,g,b,a]
    if (node.c && Array.isArray(node.c.k)) {
      const k = node.c.k;
      if (k.length === 3) {
        node.c.k = [rgb.r, rgb.g, rgb.b];
      } else if (k.length === 4) {
        node.c.k = [rgb.r, rgb.g, rgb.b, k[3]]; // 保留原 alpha
      }
    }
  };

  const overrideGradient = (node) => {
    // 渐变填充/描边：node.g?.k 是数组，结构为 [pos, r, g, b, pos, r, g, b, ...]
    if (node.g && Array.isArray(node.g.k)) {
      const arr = node.g.k;
      for (let i = 0; i < arr.length; i += 4) {
        // 跳过位置分量，覆盖颜色分量
        if (typeof arr[i] === 'number' && i + 3 < arr.length) {
          arr[i + 1] = rgb.r;
          arr[i + 2] = rgb.g;
          arr[i + 3] = rgb.b;
        }
      }
    }
  };

  const traverse = (node) => {
    if (!node || typeof node !== 'object') return;

    overrideSolid(node);
    overrideGradient(node);

    if (Array.isArray(node)) {
      node.forEach(traverse);
    } else {
      Object.keys(node).forEach((key) => traverse(node[key]));
    }
  };

  traverse(clone);
  return clone;
}

const LoadingSpinner = ({ size = 100, color = 'white', animating = true, speed = 2 }) => {
  if (!animating) return null;

  const coloredSource = useMemo(() => colorizeLottieJson(spinnerJson, color), [color]);

  return (
    <View style={{ width: size, height: size, justifyContent: 'center', alignItems: 'center' }}>
      <LottieView
        source={coloredSource}
        style={{ width: size, height: size }}
        autoPlay
        loop
        speed={speed}
      />
    </View>
  );
};

export default LoadingSpinner;