import { dimensions_t, length_t } from "@/lib/product";
import { Length } from "convert";
import { useState } from "react";
import { StyleSheet, Text, TextInput, View } from "react-native";

export type t_length_unit = "foot" | "inch"

export type MeasurementInputProps = {
    onValueSet?: (d: dimensions_t) => any,
    defaultValue: length_t;
    label?: string,
}

export function MeasurementInput({onValueSet, defaultValue, label}: MeasurementInputProps) {

    const [mValue, setMValue] = useState(defaultValue)
    const defValue = Number.isNaN(defaultValue.l) ? 0 : defaultValue.l

    function doOnValueSet(value : string) {
        setMValue(mValue);
        const iVal = parseFloat(value) || parseInt(value);
        onValueSet && onValueSet({
            ...defaultValue,
            l: iVal,
        })
    }

    const sDefValue = new String(defValue).valueOf()

    return (
        <View style={styles.inputWrapper}>
            <TextInput
                clearTextOnFocus={true}
                defaultValue={sDefValue}
                onChangeText={doOnValueSet}
                inputMode='decimal'
                style={styles.lengthInput}
                aria-label={label || "Enter measurement"}
                />
            <Text style={styles.unitHints}>{mValue.u}</Text>
        </View>
    )
}

const styles = StyleSheet.create({
    inputWrapper: {
        alignItems: "flex-start",
        flexDirection: "row"
    },
    unitHints: {
      padding: 10,
    },
    lengthInput: {
      borderWidth: 1,
      borderRadius: 4,
      borderColor: "grey",
      padding: 4,
      margin: 4,
      fontSize: 25,
      width: 100,
    },
})