import { BottomSheet, BottomSheetTextInput } from '@/aesthetics/BottomSheet';
import { Text } from '@/aesthetics/Text';
import { buttonHeight, font, radius, spacing, useColors } from '@/aesthetics/styles';
import { useStrings } from '@/common/hooks/useStrings';
import { useState } from 'react';
import { Pressable, StyleSheet, View } from 'react-native';
import { isUnitPrefix } from './constants';

type NumberMemoLoggerProps = {
  visible: boolean;
  title: string;
  unit?: string;
  onConfirm: (value: number) => void;
  onClose: () => void;
};

export function NumberMemoLogger({
  visible,
  title,
  unit,
  onConfirm,
  onClose,
}: NumberMemoLoggerProps) {
  const c = useColors();
  const strings = useStrings();
  const [value, setValue] = useState('');
  const isPrefix = isUnitPrefix(unit);

  const handleClose = () => {
    setValue('');
    onClose();
  };

  const handleConfirm = () => {
    if (!value.trim()) return;
    onConfirm(parseFloat(value) || 0);
    setValue('');
  };

  return (
    <BottomSheet visible={visible} onClose={handleClose} title={title}>
      <View style={styles.container}>
        <View style={[styles.inputRow, { backgroundColor: c.tagBg }]}>
          {isPrefix && <Text style={[styles.unitLabel, { color: c.text }]}>{unit}</Text>}
          <BottomSheetTextInput
            style={[styles.input, { color: c.text }]}
            placeholder="0"
            placeholderTextColor={c.tertiaryText}
            value={value}
            onChangeText={setValue}
            keyboardType="decimal-pad"
            autoFocus
          />
          {unit && !isPrefix && (
            <Text style={[styles.unitLabel, { color: c.secondaryText }]}>{unit}</Text>
          )}
        </View>
        <Pressable
          onPress={handleConfirm}
          disabled={!value.trim()}
          style={({ pressed }) => [
            styles.confirmBtn,
            { backgroundColor: c.accent },
            pressed && { opacity: 0.8 },
            !value.trim() && { opacity: 0.4 },
          ]}
        >
          <Text style={[styles.confirmBtnText, { color: c.onAccent }]}>
            {strings.userCustomLogs.log}
          </Text>
        </Pressable>
      </View>
    </BottomSheet>
  );
}

const styles = StyleSheet.create({
  container: { gap: spacing.lg },
  inputRow: {
    flexDirection: 'row',
    alignItems: 'center',
    borderRadius: radius.md,
    paddingHorizontal: spacing.lg,
  },
  input: { flex: 1, paddingVertical: spacing.md, fontSize: font.lg },
  unitLabel: { fontSize: font.lg, fontWeight: '500' },
  confirmBtn: {
    minHeight: buttonHeight.md,
    paddingVertical: spacing.md,
    borderRadius: radius.md,
    alignItems: 'center',
    justifyContent: 'center',
  },
  confirmBtnText: { fontSize: font.md, fontWeight: '600' },
});
