import React, { FC, ReactNode } from "react";
import { IconCheck, IconEdit, IconTrash } from "@tabler/icons-react";
import { Divider, Flex, Group, Stack, TextInput } from "@mantine/core";
import { useSelectEditorContext } from "@/app/attributes/drawers/AttrSelectEditorDrawer/contexts/SelectEditorContext";
import ActionIconWithTip from "@/components/ui/ActionIconWithTip/ActionIconWithTip";
import { AttrOptionSchema } from "@/lib/client";

type Props = {
    option: AttrOptionSchema;
    renderDraggable?: (item: AttrOptionSchema) => ReactNode;
};

const OptionTableRow: FC<Props> = ({ option, renderDraggable }) => {
    const {
        optionsActions: {
            onStartEditing,
            onFinishEditing,
            onDelete,
            editingOptionsData,
            setEditingOptionsData,
        },
    } = useSelectEditorContext();

    const onChange = (
        e: React.ChangeEvent<HTMLInputElement>,
        optionId: number
    ) => {
        setEditingOptionsData(prev => {
            prev.set(optionId, e.currentTarget.value);
            return new Map(prev);
        });
    };

    return (
        <Stack
            gap={"xs"}
            mt={"xs"}>
            <Group
                wrap={"nowrap"}
                justify={"space-between"}>
                <Group wrap={"nowrap"}>
                    {renderDraggable && renderDraggable(option)}
                    {editingOptionsData.has(option.id) ? (
                        <TextInput
                            value={editingOptionsData.get(option.id)}
                            onChange={e => onChange(e, option.id)}
                        />
                    ) : (
                        option.name
                    )}
                </Group>
                <Flex
                    justify={"center"}
                    gap={"xs"}>
                    {editingOptionsData.has(option.id) ? (
                        <ActionIconWithTip
                            onClick={() => onFinishEditing(option)}
                            tipLabel={"Сохранить"}>
                            <IconCheck />
                        </ActionIconWithTip>
                    ) : (
                        <ActionIconWithTip
                            onClick={() => onStartEditing(option)}
                            tipLabel={"Редактировать"}>
                            <IconEdit />
                        </ActionIconWithTip>
                    )}

                    <ActionIconWithTip
                        color={"red"}
                        onClick={() => onDelete(option)}
                        tipLabel={"Удалить"}>
                        <IconTrash />
                    </ActionIconWithTip>
                </Flex>
            </Group>
            <Divider />
        </Stack>
    );
};

export default OptionTableRow;
