import { dimensions_t, length_t } from "@/lib/product";
import { Length } from "convert";
import { Measure, Unit, length as en_length, area as en_area } from "enheter";
import { useState } from "react";
import { Button, StyleSheet, Text, TextInput, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

export type t_length_unit = "foot" | "inch"
export type mode = "length" | "area"

export type LengthInputProps = {
    onMeasurementSet?: (d : dimensions_t) => any,
    isArea?: boolean,
}

export function MeasurementInput(props: LengthInputProps) {

    const [length, setLength] = useState(null as null | number);
    const [width, setWidth] = useState(null as null | number);
    const [unit, setUnit] = useState("foot" as Length);

    function doSetLength(text: string) {
        const value = parseFloat(text);
        setLength(value);
        if (!props.isArea) {
            const len = en_length(unit, value)
            props.onMeasurementSet && props.onMeasurementSet(len)
        } else {
            const en_unit = unit == "foot" ? "squareFoot" : "squareInch"
            const ar = en_area(en_unit, value);
            props.onMeasurementSet && props.onMeasurementSet(ar);
        }
    }

    function doSetWidth(text: string) {
        const value = parseFloat(text);
        setLength(value);
        const len = en_length(unit, value)
        props.onMeasurementSet && props.onMeasurementSet(len)
    }

    return (
        <SafeAreaView>
            <View style={styles.inputRow}>
                <TextInput
                    keyboardType="number-pad"
                    onTouchEnd={() => setLength(null)}
                    value={length?.toString() || ""}
                    onChangeText={doSetLength}
                    style={styles.textInput}
                />
                {props.isArea &&
                    (<TextInput
                        keyboardType="number-pad"
                        onTouchEnd={() => setWidth(null)}
                        value={length?.toString() || ""}
                        onChangeText={doSetWidth}
                        style={styles.textInput}
                    />)
                }
                <Text style={styles.valueHint}>{unit == "foot" ? "ft" : "in"}</Text>
                <Button
                    title="Ft"
                    onPress={() => setUnit("foot")}
                    color={unit === "foot" ? "blue" : "gray"}
                />
                <Button
                    title="In"
                    onPress={() => setUnit("inch")}
                    color={unit === "inch" ? "blue" : "gray"}
                />
            </View>
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    textInput: {
        flexGrow: 1,
    },
    inputRow: {
        flexDirection: "row"
    },
    valueHint: {
        color: "grey",
        margin: 5,
    }
})