import {FC, useEffect, useState} from "react";
import {ActionIcon, Button, Flex, rem, TextInput} from "@mantine/core";
import {BarcodeTemplateAdditionalAttributeSchema} from "../../../../client";
import {IconX} from "@tabler/icons-react";
import {isEqual} from "lodash";

type FieldType = BarcodeTemplateAdditionalAttributeSchema;
type Props = {
    onChange: (value: FieldType[]) => void;
    value?: FieldType[];
    error?: string | null;
}
const BarcodeTemplateAdditionalFieldTable: FC<Props> = (props: Props) => {
    const {value, onChange} = props;
    const [innerValue, setInnerValue] = useState<FieldType[]>(props.value || []);
    const onNameChange = (field: FieldType, newName: string) => {
        const newField = {...field, name: newName};
        const newFields = innerValue.map(f => f === field ? newField : f);
        setInnerValue(newFields);
        onChange(newFields);
    }
    const onValueChange = (field: FieldType, newValue: string) => {
        const newField = {...field, value: newValue};
        const newFields = innerValue.map(f => f === field ? newField : f);
        setInnerValue(newFields);
        onChange(newFields);
    }
    const onCreateField = () => {
        const newField = {name: "", value: ""};
        setInnerValue([...innerValue, newField]);
        onChange([...innerValue, newField]);
    }
    const onDeleteField = (field: FieldType) => {
        const newFields = innerValue.filter(f => f !== field);
        setInnerValue(newFields);
        onChange(newFields);
    }
    useEffect(() => {
        if (isEqual(value, innerValue)) return;
        setInnerValue(value || []);
    }, [value]);
    return (
        <>
            <Flex
                direction={"column"}
                gap={rem(10)}
            >
                {/*{innerValue.length === 0 && <Text>Дополнительных полей нет</Text>}*/}
                {innerValue.map((field, idx) => (
                    <Flex align={"center"} gap={rem(10)} key={idx}>
                        <ActionIcon onClick={() => onDeleteField(field)} variant={"default"}>
                            <IconX/>
                        </ActionIcon>
                        <TextInput
                            placeholder={"Название атрибута"}
                            value={field.name}
                            onChange={event => event &&
                                onNameChange(field, event.target.value)}/>
                        <TextInput
                            placeholder={"Значение атрибута"}
                            value={field.value}
                            onChange={event => event &&
                                onValueChange(field, event.target.value)}
                        />
                    </Flex>
                ))
                }
                <Button variant={"default"} onClick={onCreateField}>Создать дополительный атрибут</Button>
            </Flex>
        </>
    )
}

export default BarcodeTemplateAdditionalFieldTable;