import React, { useContext, useState } from 'react';
import { useHistory } from 'react-router-dom';
import ExitModalContext from 'src/components/exitModalContext';
import {
    ROUTE_CREATE_BUNDLE_AUDIO_VIDEO,
    ROUTE_CREATE_BUNDLE_VIDEO_ONLY,
} from 'src/constants';
import { BundleType } from 'src/data/globalTypes';
import { useCreateBundledProductMutation } from 'src/data/mutations/createBundledProduct';
import SuccessPage from 'src/pages/createPage/successPage';
import CreateBundlePage from './createPage';

interface CreatePageProps {
    bundleType: BundleType;
}

const CreatePage = (props: CreatePageProps) => {
    const history = useHistory();
    const { bundleType } = props;

    const { setUseExitModal } = useContext(ExitModalContext);

    const [bundledProductId, setBundledProductId] = useState<string | null>(
        null
    );

    const handleSubmitBundledProduct = (productId: string | null) => {
        if (productId) {
            setUseExitModal(false);
            setBundledProductId(productId);
        }
    };

    const createBundledProduct = useCreateBundledProductMutation(
        handleSubmitBundledProduct
    );

    const handleCreateBundle = (
        audioProductId: string,
        volumes: string[][],
        selectedThumbnailId: string
    ) => {
        createBundledProduct(
            audioProductId,
            bundleType,
            volumes,
            selectedThumbnailId
        );
    };

    const handleCreateAnotherBundle = (
        newBundleType: BundleType | undefined
    ) => {
        if (newBundleType) {
            setBundledProductId(null);
            if (newBundleType === BundleType.AUDIO_VIDEO) {
                history.push(ROUTE_CREATE_BUNDLE_AUDIO_VIDEO);
            } else {
                history.push(ROUTE_CREATE_BUNDLE_VIDEO_ONLY);
            }
        }
    };

    return (
        <div className="create-bundle">
            {bundledProductId ? (
                <SuccessPage
                    productId={bundledProductId}
                    handleCreateAnotherBundle={handleCreateAnotherBundle}
                />
            ) : (
                <CreateBundlePage
                    handleCreateBundle={handleCreateBundle}
                    bundleType={bundleType}
                />
            )}
        </div>
    );
};

export default CreatePage;
