import { AttributeSchema } from "../../../client";
import { Checkbox, Group, NumberInput, TextInput, Tooltip } from "@mantine/core";
import { UseFormReturnType } from "@mantine/form";
import { DatePickerInput, DateTimePicker } from "@mantine/dates";
import { CardGeneralFormType } from "../../../pages/CardsPage/drawers/CardEditDrawer/tabs/GeneralTab/GeneralTab.tsx";
import { IconInfoCircle } from "@tabler/icons-react";

type Props = {
    attribute: AttributeSchema;
    form: UseFormReturnType<CardGeneralFormType>;
}

const CardAttributeField = ({ attribute, form }: Props) => {
    const type = attribute.type.type;

    const getDateValue = (): Date | null => {
        const value = form.getInputProps(attribute.name).value;
        if (!value) return null;
        return new Date(value);
    };

    const label = (
        <Group gap={5} align={"flex-start"}>
            {attribute.label}
            {attribute.description && (
                <Tooltip label={attribute.description} withArrow>
                    <IconInfoCircle size={18} />
                </Tooltip>
            )}
        </Group>
    );

    if (type === "bool") {
        return (
            <Checkbox
                label={label}
                {...form.getInputProps(attribute.name, { type: "checkbox" })}
            />
        );
    }
    if (type === "date") {
        return (
            <DatePickerInput
                label={label}
                {...form.getInputProps(attribute.name)}
                value={getDateValue()}
                clearable
                locale={"ru-RU"}
                valueFormat="DD.MM.YYYY"
            />
        );
    }
    if (type === "datetime") {
        return (
            <DateTimePicker
                label={label}
                {...form.getInputProps(attribute.name)}
                value={getDateValue()}
                clearable
                locale={"ru-RU"}
                valueFormat="DD.MM.YYYY HH:mm"
            />
        );
    }
    if (type === "str") {
        return (
            <TextInput
                label={label}
                {...form.getInputProps(attribute.name)}
                value={form.getInputProps(attribute.name).value ?? ""}
            />
        );
    }
    if (type === "int" || type === "float") {
        return (
            <NumberInput
                allowDecimal={type === "float"}
                label={label}
                {...form.getInputProps(attribute.name)}
            />
        );
    }
};

export default CardAttributeField;
