"use client";

import { IconCheck } from "@tabler/icons-react";
import { Group, SelectProps } from "@mantine/core";
import ObjectSelect, {
    ObjectSelectProps,
} from "@/components/selects/ObjectSelect/ObjectSelect";
import DealTag from "@/components/ui/DealTag/DealTag";
import { DealTagColorSchema } from "@/lib/client";
import useTagColorList from "../hooks/useTagColorList";

type Props = Omit<
    ObjectSelectProps<DealTagColorSchema>,
    "data" | "getValueFn" | "getLabelFn"
>;

const TagColorInput = (props: Props) => {
    const { colors } = useTagColorList();
    const colorsMap = new Map<string, DealTagColorSchema>(
        colors.map(
            color =>
                [color.id.toString(), color] as [string, DealTagColorSchema]
        )
    );

    const renderSelectOption: SelectProps["renderOption"] = ({
        option,
        checked,
    }) => {
        const tag = {
            id: Number(option.value),
            name: "Тег-пример",
            tagColor: colorsMap.get(option.value),
        };

        return (
            <Group
                flex="1"
                gap="md">
                <DealTag tag={tag} />
                {option.label}
                {checked && <IconCheck style={{ marginInlineStart: "auto" }} />}
            </Group>
        );
    };

    return (
        <ObjectSelect
            label={"Цвет"}
            renderOption={renderSelectOption}
            data={colors}
            getValueFn={color => color.id.toString()}
            getLabelFn={color => color.label}
            searchable
            {...props}
        />
    );
};

export default TagColorInput;
