import React, { FC, useEffect, useState } from "react";
import { IconCheckbox, IconTrash } from "@tabler/icons-react";
import classNames from "classnames";
import { useContextMenu } from "mantine-contextmenu";
import { Flex, Stack, TextInput } from "@mantine/core";
import { useDebouncedValue } from "@mantine/hooks";
import GroupMenu from "@/app/deals/components/mobile/GroupMenu/GroupMenu";
import DealCard from "@/app/deals/components/shared/DealCard/DealCard";
import { useDealsContext } from "@/app/deals/contexts/DealsContext";
import DealTags from "@/components/ui/DealTags/DealTags";
import useIsMobile from "@/hooks/utils/useIsMobile";
import GroupWithDealsSchema from "@/types/GroupWithDealsSchema";
import styles from "./DealsGroup.module.css";

type Props = {
    group: GroupWithDealsSchema;
};

const DealsGroup: FC<Props> = ({ group }) => {
    const [groupName, setGroupName] = useState(group.name ?? "");
    const [debouncedGroupName] = useDebouncedValue(groupName, 600);
    const {
        groupsCrud,
        groupDealsSelection: {
            startSelectingWithExistingGroup,
            selectedGroupId,
        },
    } = useDealsContext();
    const { showContextMenu } = useContextMenu();
    const isMobile = useIsMobile();

    useEffect(() => {
        if (debouncedGroupName === group.name) return;
        groupsCrud.onUpdate(group.id, { name: debouncedGroupName });
    }, [debouncedGroupName]);

    const dealContextMenu = isMobile
        ? []
        : [
              {
                  key: "delete",
                  onClick: () => groupsCrud.onDelete(group.id),
                  title: "Удалить группу",
                  icon: <IconTrash />,
              },
              {
                  key: "startDealsSelecting",
                  onClick: () => startSelectingWithExistingGroup(group),
                  title: "Добавить/удалить сделки",
                  icon: <IconCheckbox />,
              },
          ];

    return (
        <Stack
            className={classNames(
                styles["group-container"],
                selectedGroupId === group.id && styles["selected-group"]
            )}
            gap={"xs"}
            bdrs={"lg"}
            p={"xs"}
            onContextMenu={showContextMenu(dealContextMenu)}>
            <Flex
                mx={"xs"}
                align={"center"}
                w={"100%"}>
                <TextInput
                    value={groupName}
                    onChange={e => setGroupName(e.target.value)}
                    variant={"unstyled"}
                    onKeyDown={e => e.stopPropagation()}
                    flex={1}
                />
                {isMobile && (
                    <GroupMenu
                        startDealsSelecting={() =>
                            startSelectingWithExistingGroup(group)
                        }
                        onDelete={() => groupsCrud.onDelete(group.id)}
                    />
                )}
            </Flex>
            {group.items.map(deal => (
                <DealCard
                    deal={deal}
                    isInGroup
                    key={deal.id}
                />
            ))}
            {group.items.length > 0 && (
                <DealTags
                    groupId={group.id}
                    tags={group.items[0].tags}
                />
            )}
        </Stack>
    );
};

export default DealsGroup;
