import { IconCategoryPlus } from "@tabler/icons-react";
import classNames from "classnames";
import { useContextMenu } from "mantine-contextmenu";
import { Box, Card, Group, Stack, Text } from "@mantine/core";
import { useDealsContext } from "@/app/deals/contexts/DealsContext";
import { useProjectsContext } from "@/app/deals/contexts/ProjectsContext";
import { useDrawersContext } from "@/drawers/DrawersContext";
import useIsMobile from "@/hooks/utils/useIsMobile";
import { DealSchema } from "@/lib/client";
import { ModuleNames } from "@/modules/modules";
import styles from "./DealCard.module.css";
import DealTags from "@/components/ui/DealTags/DealTags";

type Props = {
    deal: DealSchema;
    isInGroup?: boolean;
};

const DealCard = ({ deal, isInGroup = false }: Props) => {
    const { selectedProject, modulesSet } = useProjectsContext();
    const { dealsCrud, refetchDeals, groupDealsSelection } = useDealsContext();
    const { openDrawer } = useDrawersContext();
    const isMobile = useIsMobile();

    const onClick = () => {
        if (groupDealsSelection.isDealsSelecting) {
            groupDealsSelection.toggleDeal(deal);
            return;
        }

        openDrawer({
            key: "dealEditorDrawer",
            props: {
                value: deal,
                onChange: deal => dealsCrud.onUpdate(deal.id, deal),
                onDelete: dealsCrud.onDelete,
                project: selectedProject,
            },
            onClose: refetchDeals,
        });
    };

    const { showContextMenu } = useContextMenu();

    const dealContextMenu =
        deal.group || isMobile
            ? []
            : [
                  {
                      key: "startGroupForming",
                      onClick: () =>
                          groupDealsSelection.startSelectingWithDeal(deal.id),
                      title: "Создать группу",
                      icon: <IconCategoryPlus />,
                  },
              ];

    const getSelectedStyles = () => {
        if (groupDealsSelection.selectedBaseDealId === deal.id) {
            return styles["container-mainly-selected"];
        }
        if (groupDealsSelection.selectedDealIds.has(deal.id)) {
            return styles["container-selected"];
        }
    };

    return (
        <Card
            onClick={onClick}
            className={classNames(
                getSelectedStyles(),
                isInGroup ? styles["container-in-group"] : styles.container
            )}
            onContextMenu={showContextMenu(dealContextMenu)}>
            <Group
                justify={"space-between"}
                wrap={"nowrap"}
                pl={"xs"}
                gap={"xs"}
                align={"start"}>
                <Text
                    c={"dodgerblue"}
                    mt={"xs"}>
                    {deal.name}
                </Text>
                <Box className={styles["deal-id"]}>
                    <Text style={{ textWrap: "nowrap" }}>ID: {deal.id}</Text>
                </Box>
            </Group>
            <Stack className={styles["deal-data"]}>
                <Stack gap={0}>
                    {modulesSet.has(ModuleNames.CLIENTS) && (
                        <Text>{deal.client?.name}</Text>
                    )}
                    {modulesSet.has(ModuleNames.FULFILLMENT_BASE) && (
                        <>
                            <Text key={"price"}>{deal.totalPrice} руб.</Text>
                            <Text key={"count"}>
                                {deal.productsQuantity} тов.
                            </Text>
                        </>
                    )}
                </Stack>
                {!deal.group && <DealTags dealId={deal.id} tags={deal.tags} />}
            </Stack>
        </Card>
    );
};

export default DealCard;
