import { useRef, useEffect, useCallback, memo, useMemo } from 'react';
import { StyleSheet, Platform } from 'react-native';
import { View } from 'tamagui';
import { wp } from '@/utils/ui/screenUtils';
import { useAppStore } from '@/stores';
import {
  CodeField,
  Cursor,
  useBlurOnFulfill,
  useClearByFocusCell,
} from 'react-native-confirmation-code-field';
import Animated, {
  useSharedValue,
  useAnimatedStyle,
  withTiming,
  Easing,
  interpolateColor,
  withRepeat,
} from 'react-native-reanimated';

const styles = StyleSheet.create({
  codeFieldRoot: {
    marginVertical: wp(20),
  },
  cell: {
    width: wp(45),
    height: wp(45),
    lineHeight: wp(43),
    fontSize: wp(18),
    fontFamily: 'Bold',
    borderWidth: wp(1),
    borderColor: '#E0E0E0',
    borderRadius: wp(8),
    backgroundColor: '#F9F9F9',
    textAlign: 'center',
    color: '#191919',
    // 为使用容器承载内容做对齐
    alignItems: 'center',
    justifyContent: 'center',
  },
  focusCell: {
    borderColor: '#007AFF',
    backgroundColor: '#FFF',
  },
  filledCell: {
    backgroundColor: '#FFF',
    borderColor: '#007AFF',
  },
  symbolText: {
    lineHeight: wp(45),
    fontSize: wp(21),
    fontFamily: 'Bold',
    textAlign: 'center',
    color: '#191919',
    includeFontPadding: Platform.select({ android: false, default: undefined }),
    textAlignVertical: Platform.select({ android: 'center', default: undefined }),
  },
  cursor: {
    width: wp(2),
    height: wp(24),
    borderRadius: wp(1),
  },
});

const CELL_COUNT = 6;
const autoComplete = Platform.select({
  android: 'sms-otp',
  default: 'one-time-code',
});

// 单个单元格组件，处理边框与字符动画
const AnimatedCell = ({
  index,
  symbol,
  isFocused,
  onLayout,
  colors,
}) => {
  const { PRIMARY, DEFAULT_BORDER, DEFAULT_BG, FOCUSED_BG } = colors;

  // 焦点/填充强度：0 -> 默认，1 -> 高亮（聚焦或已填充）
  const highlight = useSharedValue((isFocused || !!symbol) ? 1 : 0);
  const charProgress = useSharedValue(symbol ? 1 : 0);
  const cursorOpacity = useSharedValue(isFocused && !symbol ? 0.2 : 0);

  useEffect(() => {
    const to = (isFocused || !!symbol) ? 1 : 0;
    highlight.value = withTiming(to, {
      duration: 220,
      easing: Easing.bezier(0.22, 0.61, 0.36, 1),
    });
  }, [isFocused, symbol, highlight]);

  useEffect(() => {
    const to = symbol ? 1 : 0;
    charProgress.value = withTiming(to, {
      duration: symbol ? 180 : 150,
      easing: Easing.bezier(0.22, 0.61, 0.36, 1),
    });
  }, [symbol, charProgress]);

  useEffect(() => {
    if (isFocused && !symbol) {
      cursorOpacity.value = 0.2;
      cursorOpacity.value = withRepeat(
        withTiming(0.6, { duration: 700, easing: Easing.inOut(Easing.quad) }),
        -1,
        true
      );
    } else {
      cursorOpacity.value = withTiming(0, { duration: 120 });
    }
  }, [isFocused, symbol, cursorOpacity]);

  const animatedBorderStyle = useAnimatedStyle(() => {
    return {
      borderColor: interpolateColor(
        highlight.value,
        [0, 1],
        [DEFAULT_BORDER, PRIMARY]
      ),
      backgroundColor: interpolateColor(
        highlight.value,
        [0, 1],
        [DEFAULT_BG, FOCUSED_BG]
      ),
    };
  });

  const animatedCharStyle = useAnimatedStyle(() => {
    return {
      opacity: charProgress.value,
      transform: [
        { scale: 0.94 + 0.06 * charProgress.value },
      ],
    };
  });

  const animatedCursorStyle = useAnimatedStyle(() => ({
    opacity: cursorOpacity.value,
  }));

  return (
    <Animated.View
      style={[styles.cell, animatedBorderStyle]}
      onLayout={onLayout}
    >
      {symbol ? (
        <Animated.Text
          allowFontScaling={false}
          maxFontSizeMultiplier={1}
          style={[styles.symbolText, animatedCharStyle]}
        >
          {symbol}
        </Animated.Text>
      ) : (
        isFocused ? (
          <Animated.View
            style={[styles.cursor, { backgroundColor: PRIMARY }, animatedCursorStyle]}
          />
        ) : null
      )}
    </Animated.View>
  );
};

export const VerificationCodeInput = ({ verificationCode, setVerificationCode, autoFocus = true, onComplete }) => {
  // 将数组格式的验证码转换为字符串格式
  const value = Array.isArray(verificationCode) ? verificationCode.join('') : verificationCode || '';
  const primaryColor = useAppStore((s) => s.primary);
  
  // 缓存颜色配置，避免频繁重新计算
  const colors = useMemo(() => ({
    PRIMARY: primaryColor || '#007AFF',
    DEFAULT_BORDER: '#E0E0E0',
    DEFAULT_BG: '#F9F9F9',
    FOCUSED_BG: '#FFFFFF',
  }), [primaryColor]);

  // 使用 ref 来存储 onComplete 回调，避免依赖变化导致重复调用
  const onCompleteRef = useRef(onComplete);
  onCompleteRef.current = onComplete;
  
  // 使用 ref 来防止重复触发 onComplete
  const hasTriggeredComplete = useRef(false);
  
  // 处理值变化，将字符串转换回数组格式以保持兼容性
  const handleValueChange = useCallback((text) => {
    const cleanValue = text.replace(/\D/g, '').slice(0, CELL_COUNT);
    const newCode = cleanValue.split('').concat(Array(CELL_COUNT - cleanValue.length).fill(''));
    setVerificationCode(newCode);
    
    // 当验证码输入完成时，触发回调（只触发一次）
    if (cleanValue.length === CELL_COUNT && onCompleteRef.current && !hasTriggeredComplete.current) {
      hasTriggeredComplete.current = true;
      onCompleteRef.current(cleanValue);
    } else if (cleanValue.length < CELL_COUNT) {
      // 重置标志，允许下次完整输入时再次触发
      hasTriggeredComplete.current = false;
    }
  }, [setVerificationCode]);

  const ref = useBlurOnFulfill({ value, cellCount: CELL_COUNT });
  const [props, getCellOnLayoutHandler] = useClearByFocusCell({
    value,
    setValue: handleValueChange,
  });

  // 自动聚焦逻辑
  useEffect(() => {
    if (autoFocus && ref.current) {
      const timer = setTimeout(() => {
        ref.current?.focus();
      }, 100);
      return () => clearTimeout(timer);
    }
  }, [autoFocus]);

  return (
    <View>
      <CodeField
        ref={ref}
        {...props}
        value={value}
        onChangeText={handleValueChange}
        cellCount={CELL_COUNT}
        rootStyle={styles.codeFieldRoot}
        keyboardType="number-pad"
        textContentType="oneTimeCode"
        autoComplete={autoComplete}
        renderCell={({ index, symbol, isFocused }) => (
          <AnimatedCell
            key={index}
            index={index}
            symbol={symbol}
            isFocused={isFocused}
            onLayout={getCellOnLayoutHandler(index)}
            colors={colors}
          />
        )}
      />
    </View>
  );
};

export default memo(VerificationCodeInput);
