import { Product } from "@/lib/product"
import { useState } from "react"
import { StyleSheet, Text, TouchableHighlight } from "react-native"
import { FlatList } from "react-native-reanimated/lib/typescript/Animated";
import ProductAttributeEditor from "./ProductAttributeEditor";

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(true);

    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);
        onProductUpdated && onProductUpdated(product_id, product);
    }

    return (
        <TouchableHighlight
            onPress={() => setShowAttributes(true)}
        >
            <Text style={styles.product}>{product.attributes.name || `Product ${product.id}`} </Text>
            {showAttributes &&
                (
                    <FlatList
                        data={product.attributesAsList}
                        renderItem={({ item }) => (
                            <ProductAttributeEditor
                                product={product}
                                key={item.key}
                                value={item.value}
                                onChange={onAttributeChanged}
                                onDelete={onAttributeDelete}
                            />
                        )}
                    />
                )
            }
        </TouchableHighlight>
    )
}

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