import {FC, useState} from "react";

import styles from './CreateDealButton.module.css';
import {Text, Transition} from '@mantine/core';
import CreateDealFrom from "../CreateDealForm/CreateDealFrom.tsx";
import {DealService} from "../../../client";
import {useQueryClient} from "@tanstack/react-query";
import {dateWithoutTimezone} from "../../../shared/lib/date.ts";

type Props = {
    onClick: () => void;
}
const CreateDealButton: FC<Props> = () => {
    const [isCreating, setIsCreating] = useState(false);
    const [isTransitionEnded, setIsTransitionEnded] = useState(true);
    const queryClient = useQueryClient();

    return (
        <div className={styles['container']}
             onClick={() => {
                 if (isCreating) return;
                 setIsCreating(prevState => !prevState)
                 setIsTransitionEnded(false);
             }}
        >
            {(!isCreating && isTransitionEnded) &&
                <Text>Быстрое добавление</Text>
            }
            <Transition
                mounted={isCreating}
                transition={"scale-y"}
                onExited={() => setIsTransitionEnded(true)}

            >
                {(styles) => (
                    <div style={styles}>
                        <CreateDealFrom
                            onCancel={() => {
                                setIsCreating(false)
                            }}
                            onSubmit={(quickDeal) => {
                                DealService.quickCreateDealQuickCreatePost({
                                    requestBody: {
                                        ...quickDeal,
                                        acceptanceDate: dateWithoutTimezone(quickDeal.acceptanceDate)
                                    }
                                }).then(async () => {
                                    await queryClient.invalidateQueries({queryKey: ['getDealSummaries']});
                                    setIsCreating(false);
                                })
                            }}
                        />
                    </div>
                )}
            </Transition>

        </div>
    )
}
export default CreateDealButton;