import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, TextInput } from 'react-native';
import { Button } from './Button';
import { colors, spacing, typography, borderRadius } from '../lib/theme';
import { Weight, WeightUnit } from '../types';
import { convertWeight } from '../lib/utils/weightConversions';

interface WeightInputProps {
  label?: string;
  value: Weight | undefined;
  onChange: (weight: Weight | undefined) => void;
  userPreferredUnit: WeightUnit;
}

export const WeightInput: React.FC<WeightInputProps> = ({
  label,
  value,
  onChange,
  userPreferredUnit,
}) => {
  const [inputValue, setInputValue] = useState('');
  const [currentUnit, setCurrentUnit] = useState<WeightUnit>(userPreferredUnit);

  useEffect(() => {
    if (value) {
      setInputValue(value.value.toString());
      setCurrentUnit(value.unit);
    } else {
      setInputValue('');
      setCurrentUnit(userPreferredUnit);
    }
  }, [value]);

  const handleValueChange = (text: string) => {
    setInputValue(text);
    const numValue = parseFloat(text);
    if (!isNaN(numValue) && numValue > 0) {
      onChange({ value: numValue, unit: currentUnit });
    } else if (text === '') {
      onChange(undefined);
    }
  };

  const handleUnitChange = (newUnit: WeightUnit) => {
    if (value) {
      const converted = convertWeight(value, newUnit);
      setInputValue(converted.value.toString());
      setCurrentUnit(newUnit);
      onChange(converted);
    } else {
      setCurrentUnit(newUnit);
    }
  };

  const unitOptions = userPreferredUnit === 'lb' || userPreferredUnit === 'oz'
    ? ['lb', 'oz'] as WeightUnit[]
    : ['kg', 'g'] as WeightUnit[];

  return (
    <View style={styles.container}>
      {label && <Text style={styles.label}>{label}</Text>}
      <View style={styles.row}>
        <TextInput
          style={styles.input}
          value={inputValue}
          onChangeText={handleValueChange}
          placeholder="0.0"
          keyboardType="decimal-pad"
        />
        <View style={styles.unitButtons}>
          {unitOptions.map(unit => (
            <Button
              key={unit}
              title={unit}
              onPress={() => handleUnitChange(unit)}
              variant={currentUnit === unit ? 'primary' : 'outline'}
              size="sm"
              style={styles.unitButton}
            />
          ))}
        </View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    marginBottom: spacing.md,
  },
  label: {
    fontSize: typography.fontSize.sm,
    fontWeight: typography.fontWeight.medium,
    color: colors.text,
    marginBottom: spacing.xs,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.sm,
  },
  input: {
    flex: 1,
    height: 48,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: borderRadius.md,
    paddingHorizontal: spacing.md,
    backgroundColor: colors.background,
    fontSize: typography.fontSize.md,
    color: colors.text,
  },
  unitButtons: {
    flexDirection: 'row',
    gap: spacing.xs,
  },
  unitButton: {
    minWidth: 50,
  },
});
