import { useState } from "react";
import { IconPlus } from "@tabler/icons-react";
import { Card, Center, Group, Text, Transition } from "@mantine/core";
import { useDealsContext } from "@/app/deals/contexts/DealsContext";
import CreateCardForm, { CreateDealForm } from "./components/CreateCardForm";
import styles from "./CreateDealButton.module.css";

const CreateCardButton = () => {
    const [isCreating, setIsCreating] = useState(false);
    const [isTransitionEnded, setIsTransitionEnded] = useState(true);
    const { dealsCrud } = useDealsContext();

    const onSubmit = (values: CreateDealForm) => {
        dealsCrud.onCreate(values);
        setIsCreating(prevState => !prevState);
        setIsTransitionEnded(false);
    };

    return (
        <Card
            className={styles["create-button"]}
            onClick={() => {
                if (isCreating) return;
                setIsCreating(prevState => !prevState);
                setIsTransitionEnded(false);
            }}>
            {!isCreating && isTransitionEnded && (
                <Center>
                    <Group gap={"xs"}>
                        <IconPlus />
                        <Text>Добавить</Text>
                    </Group>
                </Center>
            )}
            <Transition
                mounted={isCreating}
                transition={"scale-y"}
                onExited={() => setIsTransitionEnded(true)}>
                {styles => (
                    <div style={styles}>
                        <CreateCardForm
                            onCancel={() => setIsCreating(false)}
                            onSubmit={onSubmit}
                        />
                    </div>
                )}
            </Transition>
        </Card>
    );
};
export default CreateCardButton;
