import { Product } from "@/lib/product"
import { useState } from "react"
import { FlatList, StyleSheet, Text, TouchableHighlight, View } from "react-native"
import { ProductAttributeEditor } from "./ProductAttributeEditor";
import { TextInput } from "react-native-gesture-handler";

export type ProductUpdatedFunc = (product_id: string, product: Product) => any;
export type ProductDeletedFunc = (product_id: string) => any;

export type ProductEditorItemProps = {
    product: Product,
    onProductUpdated?: ProductUpdatedFunc,
    onProductDeleted?: ProductDeletedFunc,
}

export const ProductEditorItem = ({ product, onProductUpdated, onProductDeleted }: ProductEditorItemProps) => {

    const [showAttributes, setShowAttributes] = useState(false);
    const [doEditName, setDoEditName] = useState(false);
    const [newName, setNewName] = useState(product.attributes.name || `Product ${product.id}`);

    function updateName(name : string) {
        setNewName(name);
        product.attributes["name"] = name;
        onProductUpdated && onProductUpdated(product.id, product);
    }

    function onAttributeChanged(product_id: string, key: string, newValue: string) {
        product.attributes[key] = newValue;
        onProductUpdated && onProductUpdated(product_id, product);

    }

    function onAttributeDelete(product_id: string, key: string) {
        product.removeAttribute(key);
        onProductDeleted && onProductDeleted(product_id);
    }

    return (
        <View>
            <TouchableHighlight
                onPress={() => setShowAttributes(!showAttributes)}
                aria-label="Product Item"
            >
                <Text style={styles.product}>{newName}</Text>
            </TouchableHighlight>
            {showAttributes &&
                (
                    <FlatList
                        data={product.attributesAsList}
                        renderItem={({ item }) => (
                            <ProductAttributeEditor
                                product={product}
                                attributeKey={item.key || "some key"}
                                attributeValue={item.value}
                                onChange={onAttributeChanged}
                                onDelete={onAttributeDelete}
                            />
                        )}
                        keyExtractor={(item) => `${product.id}-${item.key}`}
                    />
                )
            }
        </View>
    )
}

const styles = StyleSheet.create({
    product: {},
})