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 { Dimensions, DimensionUnit } from '../types';

interface DimensionsInputProps {
  label?: string;
  value: Dimensions | undefined;
  onChange: (dims: Dimensions | undefined) => void;
  userPreferredUnit: DimensionUnit;
}

export const DimensionsInput: React.FC<DimensionsInputProps> = ({
  label,
  value,
  onChange,
  userPreferredUnit,
}) => {
  const [height, setHeight] = useState('');
  const [width, setWidth] = useState('');
  const [diameter, setDiameter] = useState('');
  const [notes, setNotes] = useState('');
  const [unit, setUnit] = useState<DimensionUnit>(userPreferredUnit);

  useEffect(() => {
    if (value) {
      setHeight(value.height?.toString() || '');
      setWidth(value.width?.toString() || '');
      setDiameter(value.diameter?.toString() || '');
      setNotes(value.notes || '');
      setUnit(value.unit);
    }
  }, [value]);

  const updateDimensions = (updates: Partial<Dimensions>) => {
    const newHeight = updates.height !== undefined ? updates.height : parseFloat(height);
    const newWidth = updates.width !== undefined ? updates.width : parseFloat(width);
    const newDiameter = updates.diameter !== undefined ? updates.diameter : parseFloat(diameter);
    const newNotes = updates.notes !== undefined ? updates.notes : notes;
    const newUnit = updates.unit !== undefined ? updates.unit : unit;

    const hasAnyValue = !isNaN(newHeight) || !isNaN(newWidth) || !isNaN(newDiameter);

    if (!hasAnyValue) {
      onChange(undefined);
      return;
    }

    onChange({
      height: !isNaN(newHeight) ? newHeight : undefined,
      width: !isNaN(newWidth) ? newWidth : undefined,
      diameter: !isNaN(newDiameter) ? newDiameter : undefined,
      unit: newUnit,
      notes: newNotes || undefined,
    });
  };

  const handleHeightChange = (text: string) => {
    setHeight(text);
    updateDimensions({ height: parseFloat(text) || undefined });
  };

  const handleWidthChange = (text: string) => {
    setWidth(text);
    updateDimensions({ width: parseFloat(text) || undefined });
  };

  const handleDiameterChange = (text: string) => {
    setDiameter(text);
    updateDimensions({ diameter: parseFloat(text) || undefined });
  };

  const handleNotesChange = (text: string) => {
    setNotes(text);
    updateDimensions({ notes: text || undefined });
  };

  const handleUnitChange = (newUnit: DimensionUnit) => {
    setUnit(newUnit);
    updateDimensions({ unit: newUnit });
  };

  return (
    <View style={styles.container}>
      {label && <Text style={styles.label}>{label}</Text>}

      <View style={styles.unitToggle}>
        <Button
          title="in"
          onPress={() => handleUnitChange('in')}
          variant={unit === 'in' ? 'primary' : 'outline'}
          size="sm"
        />
        <Button
          title="cm"
          onPress={() => handleUnitChange('cm')}
          variant={unit === 'cm' ? 'primary' : 'outline'}
          size="sm"
        />
      </View>

      <View style={styles.row}>
        <View style={styles.field}>
          <Text style={styles.fieldLabel}>Height</Text>
          <TextInput
            style={styles.input}
            value={height}
            onChangeText={handleHeightChange}
            placeholder="0.0"
            keyboardType="decimal-pad"
          />
        </View>

        <View style={styles.field}>
          <Text style={styles.fieldLabel}>Width</Text>
          <TextInput
            style={styles.input}
            value={width}
            onChangeText={handleWidthChange}
            placeholder="0.0"
            keyboardType="decimal-pad"
          />
        </View>

        <View style={styles.field}>
          <Text style={styles.fieldLabel}>Diameter</Text>
          <TextInput
            style={styles.input}
            value={diameter}
            onChangeText={handleDiameterChange}
            placeholder="0.0"
            keyboardType="decimal-pad"
          />
        </View>
      </View>

      <TextInput
        style={styles.notesInput}
        value={notes}
        onChangeText={handleNotesChange}
        placeholder="Dimension notes (optional)"
        multiline
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    marginBottom: spacing.md,
  },
  label: {
    fontSize: typography.fontSize.sm,
    fontWeight: typography.fontWeight.medium,
    color: colors.text,
    marginBottom: spacing.xs,
  },
  unitToggle: {
    flexDirection: 'row',
    gap: spacing.xs,
    marginBottom: spacing.sm,
  },
  row: {
    flexDirection: 'row',
    gap: spacing.sm,
    marginBottom: spacing.sm,
  },
  field: {
    flex: 1,
  },
  fieldLabel: {
    fontSize: typography.fontSize.xs,
    color: colors.textSecondary,
    marginBottom: spacing.xs,
  },
  input: {
    height: 40,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: borderRadius.md,
    paddingHorizontal: spacing.sm,
    backgroundColor: colors.background,
    fontSize: typography.fontSize.md,
    color: colors.text,
  },
  notesInput: {
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: borderRadius.md,
    padding: spacing.sm,
    backgroundColor: colors.background,
    fontSize: typography.fontSize.sm,
    color: colors.text,
    minHeight: 60,
  },
});
