import { CardAttributeSchema, CardSummary } from "../../../../client";
import { Flex, Text } from "@mantine/core";
import { formatDate, formatDateTime } from "../../../../types/utils.ts";
import { useProjectsContext } from "../../../../contexts/ProjectsContext.tsx";

type Props = {
    cardSummary: CardSummary;
}

const CardAttributesInSummaryItem = ({ cardSummary }: Props) => {
    const { selectedProject } = useProjectsContext();

    const attributeIds = new Set(selectedProject?.attributes.map(attr => attr.id));

    const getAttrValueValue = (cardAttr: CardAttributeSchema) => {
        const value = cardAttr.value;
        if (value === null) return;

        const type = cardAttr.attribute.type.type;
        if (type === "datetime") {
            return formatDateTime(value as string);
        }
        if (type === "date") {
            return formatDate(value as string);
        }
        if (type === "bool") {
            return value ? "да" : "нет";
        }

        return value;
    };

    const isHighlightNeeded = (cardAttr: CardAttributeSchema): boolean => {
        const type = cardAttr.attribute.type.type;
        if (!cardAttr.attribute.isHighlightIfExpired) return false;
        if (type !== "datetime" && type !== "date") return false;

        const datetime = new Date(cardAttr.value as string);
        const curr = new Date();
        if (type === "datetime") {
            return datetime < curr;
        }

        curr.setHours(0, 0, 0, 0);
        return datetime < curr;
    };

    return (
        <Flex direction={"column"}>
            {cardSummary.attributes
                .filter(cardAttr => (
                    cardAttr.attribute.isShownOnDashboard &&
                    cardAttr.value !== null &&
                    attributeIds.has(cardAttr.attribute.id)
                ))
                .map(cardAttr => {
                    const isHighlight = isHighlightNeeded(cardAttr);
                    return (
                        <Text
                            key={cardAttr.attribute.id}
                            c={isHighlight ? "red" : "gray.6"}
                            size={"sm"}
                        >
                            {cardAttr.attribute.label}: {getAttrValueValue(cardAttr)}
                        </Text>
                    );
                })
            }
        </Flex>
    );
};

export default CardAttributesInSummaryItem;
