/* 
  Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  
  Licensed under the Apache License, Version 2.0 (the "License").
  You may not use this file except in compliance with the License.
  You may obtain a copy of the License at
  
      http://www.apache.org/licenses/LICENSE-2.0
  
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
import { FunctionComponent, useState } from 'react';
import { generatePath, useHistory } from 'react-router-dom';
import { v4 as uuidv4 } from 'uuid';

import { useAppLayoutContext } from 'aws-northstar/layouts/AppLayout';

import PageLoading from '@ags/webclient-core/components/PageLoading';
import { MutationType } from '@ags/webclient-risks-core/queries';
import { useAgsMutation } from '@ags/webclient-core/queries';
import {
    CreateControlTechniqueParams,
    CreateControlTechniqueResponse,
} from '@ags/webclient-risks-core/types';

import ControlTechniqueForm from '@ags/webclient-risks-view/components/ControlTechniques/Form';
import { ROUTE_CONTROL_TECHNIQUE_DETAILS } from '@ags/webclient-risks-core/config/routes';

const defaultValue = {
    name: '',
    description: '',
    controlType: 'DETECTIVE',
    enabled: true,
    techniqueDetails: {
        integrationType: 'NONE',
    },
};

const ControlTechniqueCreate: FunctionComponent = () => {
    const history = useHistory();
    const { addNotification } = useAppLayoutContext();
    const [input, setInput] = useState<CreateControlTechniqueParams>(defaultValue);

    const mutation = useAgsMutation<
        CreateControlTechniqueResponse,
        CreateControlTechniqueParams,
        Error
    >(MutationType.CREATE_CONTROLTECHNIQUE, {
        onSuccess: (data: CreateControlTechniqueResponse) => {
            const path = generatePath(ROUTE_CONTROL_TECHNIQUE_DETAILS, {
                controlTechniqueId: data.id,
            });

            history.replace(path, {
                notifications: [
                    {
                        id: uuidv4(),
                        type: 'success',
                        header: `Create Control Technique ${data.name} Succeeded.`,
                        dismissible: true,
                    },
                ],
            });
        },
        onError: (error: Error, params: CreateControlTechniqueParams) => {
            addNotification({
                id: uuidv4(),
                type: 'error',
                header: `Create Control Technique ${params.name} Failed.`,
                content: error.message,
                dismissible: true,
            });
        },
    });

    const handleCancel = () => {
        history.goBack();
    };

    const handleSubmit = (values: Record<string, any>) => {
        const detailsData: {
            restEndpoint?: string;
            eventBus?: string;
            detailType?: string;
            awsPolicyArn?: string;
        } = {};

        switch (values.techniqueDetails.integrationType) {
            case 'REST':
                detailsData.restEndpoint = values.techniqueDetails.restEndpoint;
                break;
            case 'EVENT':
                detailsData.eventBus = values.techniqueDetails.eventBus;
                detailsData.detailType = values.techniqueDetails.detailType;
                break;
            case 'AWS_IAM':
            case 'AWS_SCP':
                detailsData.awsPolicyArn = values.techniqueDetails.awsPolicyArn;
        }

        const request = {
            name: values.name,
            description: values.description,
            controlType: values.controlType,
            enabled: values.enabled,
            techniqueDetails: {
                integrationType: values.techniqueDetails.integrationType,
                policyId: values.techniqueDetails.policyId,
                bundleName: values.techniqueDetails.bundleName,
                namespace: values.techniqueDetails.namespace,
                cpSourceUrls: values.techniqueDetails.cpSourceUrls,
                configRuleArn: values.techniqueDetails.configRuleArn,
                ...detailsData,
            },
        };
        setInput(request);
        handleCreateControlTechnique(request);
    };

    const handleCreateControlTechnique = (request: CreateControlTechniqueParams) => {
        mutation.mutate(request);
    };

    // page
    if (mutation.isLoading) {
        return <PageLoading />;
    }

    const initialValues = input ?? defaultValue;
    return (
        <ControlTechniqueForm
            onSubmit={handleSubmit}
            onCancel={handleCancel}
            initialValues={initialValues}
        />
    );
};

export default ControlTechniqueCreate;
