import { useEffect, useRef } from 'react';
import { Animated, Text, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import { useColors } from '../../lib/theme';

interface DeviceProgressBarProps {
  count: number;
  max: number;
  atLimit: boolean;
}

export function DeviceProgressBar({ count, max, atLimit }: DeviceProgressBarProps) {
  const { t } = useTranslation();
  const colors = useColors();
  const fillAnim = useRef(new Animated.Value(0)).current;

  const ratio = max > 0 ? Math.min(count / max, 1) : 0;

  useEffect(() => {
    Animated.timing(fillAnim, {
      toValue: ratio,
      duration: 380,
      useNativeDriver: false,
    }).start();
  }, [ratio]);

  const fillColor = atLimit ? colors.brandOrange : colors.success;

  return (
    <View style={{ gap: 5 }}>
      <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
        <Text
          style={{
            fontSize: 12,
            color: atLimit ? colors.brandOrange : colors.textMuted,
            fontFamily: 'Nunito_600SemiBold',
          }}
        >
          {atLimit
            ? t('devices.progress_at_limit')
            : t('devices.progress_label', { count, max })}
        </Text>
        <Text
          style={{
            fontSize: 11,
            color: colors.textMuted,
            fontFamily: 'Nunito_400Regular',
          }}
        >
          {count}/{max}
        </Text>
      </View>

      <View
        style={{
          height: 6,
          borderRadius: 3,
          backgroundColor: colors.surfaceElevated,
          overflow: 'hidden',
        }}
      >
        <Animated.View
          style={{
            height: '100%',
            borderRadius: 3,
            backgroundColor: fillColor,
            width: fillAnim.interpolate({
              inputRange: [0, 1],
              outputRange: ['0%', '100%'],
            }),
          }}
        />
      </View>
    </View>
  );
}
