import React, { useEffect, useRef, useState } from 'react';
import { Animated, Text, View } from 'react-native';
import { useTheme } from '../../theme';
import { Touchable } from './Touchable';

export interface SegmentedOption {
  key: string;
  label: string;
}

interface SegmentedControlProps {
  options: SegmentedOption[];
  /** 当前选中项的 key */
  value: string;
  onChange: (key: string) => void;
}

/** 指示器与容器之间的内缩间距（dp） */
const INDICATOR_INSET = 3;

/**
 * 分段选择器（主题化，带 Animated spring 滑动指示器）。
 * 用于替代手写 tab 切换：等宽分段、胶囊容器、选中项高亮滑动。
 */
export function SegmentedControl({ options, value, onChange }: SegmentedControlProps) {
  const { theme } = useTheme();
  const [containerWidth, setContainerWidth] = useState(0);
  const translateX = useRef(new Animated.Value(0)).current;
  /** 首次布局时直接落位，不播放滑动动画 */
  const initializedRef = useRef(false);

  const count = options.length;
  const innerWidth = Math.max(0, containerWidth - INDICATOR_INSET * 2);
  const segmentWidth = count > 0 ? innerWidth / count : 0;
  const activeIndex = Math.max(0, options.findIndex(option => option.key === value));

  // 选中项或布局宽度变化时，弹性滑动指示器到目标分段
  useEffect(() => {
    if (segmentWidth <= 0) return;
    const toValue = activeIndex * segmentWidth;
    if (!initializedRef.current) {
      initializedRef.current = true;
      translateX.setValue(toValue);
      return;
    }
    Animated.spring(translateX, {
      toValue,
      tension: 170,
      friction: 14,
      useNativeDriver: true,
    }).start();
  }, [activeIndex, segmentWidth, translateX]);

  return (
    <View
      accessibilityRole="tablist"
      onLayout={event => setContainerWidth(event.nativeEvent.layout.width)}
      style={{
        flexDirection: 'row',
        backgroundColor: theme.colors.bgTertiary,
        borderRadius: theme.radii.full,
        padding: INDICATOR_INSET,
      }}
    >
      {/* 滑动指示器：完成布局测量后才渲染，避免首帧宽度为 0 */}
      {segmentWidth > 0 && (
        <Animated.View
          style={{
            position: 'absolute',
            top: INDICATOR_INSET,
            bottom: INDICATOR_INSET,
            left: INDICATOR_INSET,
            width: segmentWidth,
            borderRadius: theme.radii.full,
            backgroundColor: theme.colors.accent,
            transform: [{ translateX }],
            ...theme.shadows.sm,
          }}
        />
      )}

      {options.map(option => {
        const active = option.key === value;
        return (
          <Touchable
            key={option.key}
            accessibilityRole="tab"
            accessibilityLabel={option.label}
            accessibilityState={{ selected: active }}
            onPress={() => onChange(option.key)}
            style={{
              flex: 1,
              minHeight: 44,
              alignItems: 'center',
              justifyContent: 'center',
              paddingVertical: theme.spacing.xs,
            }}
          >
            <Text
              style={{
                fontSize: theme.typography.bodySmall.fontSize,
                fontWeight: '600',
                color: active ? theme.colors.fgInverse : theme.colors.fgSecondary,
              }}
            >
              {option.label}
            </Text>
          </Touchable>
        );
      })}
    </View>
  );
}
