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,
    units?: Length,
}

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

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

    units = units || "ft";

    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}>{units}</Text>
        </View>
    )
}

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