import React, { useState, useEffect, useCallback } from 'react';
import { FluentTextField } from '../inputs/textField/FluentTextField';
import { FluentTextFieldAutoComplete } from '../inputs/textField/FluentTextFieldAutoComplete';
import { LayoutUnit } from '../../layout/LayoutUnit';
import { DragDropFileUpload } from '../../uploader/DragDropFileUpload';
import { Form, FormButtons, SubmitButton, Field } from '../../utilities/form';
import { useUser } from '../../utilities/auth/useUser';
import { useTranslation } from 'react-i18next';
import { useSnackbar } from 'notistack';
import { Button } from '@material-ui/core';
import { apiMutate } from '../../utilities/useAxiosMutate';
import { AmbientCard } from '../surfaces/cards/AmbientCard';
import { LinearProgress } from '../../UI/loading/LinearProgress';
import { useHistory } from 'react-router-dom';
import { ConfigService } from '../../configService';
const SupportCaseForm = ({ onSubmit, initialValues = {}, handleCloseSupportCaseSideSheet }) => {
    const { t } = useTranslation();
    const user = useUser();
    const { enqueueSnackbar, closeSnackbar } = useSnackbar();
    const [severityOptions, setSeverityOptions] = useState([]);
    const [environmentOptions, setEnvironmentOptions] = useState([]);
    const [brandOptions, setBrandOptions] = useState([]);
    const [uploadedFiles, setUploadedFiles] = useState([]);
    const [unityState, setUnityState] = useState();
    const [loadingState, setLoadingState] = useState(false);
    const baseUrl = ConfigService.productV1ApiUrl; // backend base url
    const unityUrl = ConfigService.supportV1ApiUrl; // unity support bypass
    const unityEnv = ConfigService.config.UNITY_ENVIRONMENT; // unity environment
    const [uploadKey, setUploadKey] = useState(0);
    const [restrictedFiles, setRestrictedFiles] = useState({});
    const history = useHistory();
    const getFileRestrictions = useCallback(async () => apiMutate(baseUrl, `udpunitysupport/supportFileUploadRestrictions`, {
        method: 'get',
        headers: {
            currentTenantId: user === null || user === void 0 ? void 0 : user.currentTenantId
        }
    }), [baseUrl, user === null || user === void 0 ? void 0 : user.currentTenantId]);
    const getFileRestrictionsUnity = useCallback(async () => apiMutate(unityUrl, `evergrncaseattachment/get-attachment-restrictions`, {
        method: 'get',
        headers: {
            currentTenantId: user === null || user === void 0 ? void 0 : user.currentTenantId
        }
    }), [unityUrl, user === null || user === void 0 ? void 0 : user.currentTenantId]);
    const getSeverityUnity = useCallback(async () => apiMutate(unityUrl, `caseseverity/get-case-severity`, {
        method: 'get',
        headers: {
            currentTenantId: user === null || user === void 0 ? void 0 : user.currentTenantId
        }
    }), [unityUrl, user === null || user === void 0 ? void 0 : user.currentTenantId]);
    const getEnvironmentUnity = useCallback(async () => apiMutate(unityUrl, `evergrncaseenvironment/get-case-environments`, {
        method: 'get',
        headers: {
            currentTenantId: user === null || user === void 0 ? void 0 : user.currentTenantId
        }
    }), [unityUrl, user === null || user === void 0 ? void 0 : user.currentTenantId]);
    const getSeverity = useCallback(async () => apiMutate(baseUrl, `udpunitysupport/severities`, {
        method: 'get',
        headers: {
            currentTenantId: user === null || user === void 0 ? void 0 : user.currentTenantId
        }
    }), [baseUrl, user === null || user === void 0 ? void 0 : user.currentTenantId]);
    const getEnvironment = useCallback(async () => apiMutate(baseUrl, `udpunitysupport/environments`, {
        method: 'get',
        headers: {
            currentTenantId: user === null || user === void 0 ? void 0 : user.currentTenantId
        }
    }), [baseUrl, user === null || user === void 0 ? void 0 : user.currentTenantId]);
    // externalUuid will be needed part of the post request to submit ticket
    const getTenantCaseAccount = useCallback(async () => apiMutate(baseUrl, `udpunitysupport/tenantCaseAccount/` + (user === null || user === void 0 ? void 0 : user.currentTenantId), {
        method: 'get',
        headers: {
            currentTenantId: user === null || user === void 0 ? void 0 : user.currentTenantId
        }
    }), [baseUrl, user === null || user === void 0 ? void 0 : user.currentTenantId]);
    // list of products to choose from when in Support Portal, if cooresponsding externalUuid is null, default to devops support GUID
    const getTenantCaseBrand = useCallback(async () => apiMutate(ConfigService.tenantV2ApiUrl, `tenant/products`, {
        method: 'get',
        headers: {
            currentTenantId: user === null || user === void 0 ? void 0 : user.currentTenantId
        }
    }), [user === null || user === void 0 ? void 0 : user.currentTenantId]);
    const getTenantSubscribedProducts = useCallback(async () => apiMutate(ConfigService.tenantV1ApiUrl, `tenantProducts?tenantId=${user === null || user === void 0 ? void 0 : user.currentTenantId}`, {
        method: 'get',
        headers: {
            currentTenantId: user === null || user === void 0 ? void 0 : user.currentTenantId
        }
    }), [user === null || user === void 0 ? void 0 : user.currentTenantId]);
    // TODO: this data should come from Unity table -> Unity UEM -> Unity Support
    const getCasesEnv = {
        Development: '100000003',
        Build: '100000003',
        Staging: '100000001',
        Production: '100000000'
    };
    function getCaseEnvironment() {
        return getCasesEnv[unityEnv] || '100000003'; // default to dev
    }
    let brandId = '416b0ca8-e679-ef11-ac20-6045bdcd3d86'; // Default to devops support ID, should come from API
    const postCaseAttachment = useCallback((values) => {
        const data = new FormData();
        uploadedFiles.forEach((file) => {
            data.append('files', file);
        });
        data.append('EvergrnCaseName', values.title);
        data.append('EvergrnDescription', values.description);
        data.append('EvergrnCaseEnvironment', getCaseEnvironment());
        data.append('EvergrnSeverity', values.severity.value);
        // Find the corresponding brand ID using environment variable's product ID
        const matchingProduct = brandOptions.find((product) => product.productId == ConfigService.config.UNITY_PRODUCT_ID);
        if (matchingProduct && matchingProduct.value) {
            brandId = matchingProduct.value;
        }
        data.append('EvergrnBrandId', brandId);
        data.append('UDPDriveUnityProductId', ConfigService.config.UNITY_PRODUCT_ID);
        return apiMutate(baseUrl, `udpunitysupport/case`, {
            method: 'post',
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }, { data: data });
    }, [baseUrl, uploadedFiles, getCaseEnvironment, brandOptions, brandId]);
    const postCaseAttachmentUnity = useCallback((values) => {
        var _a;
        const data = new FormData();
        uploadedFiles.forEach((file) => {
            data.append('files', file);
        });
        data.append('EvergrnCaseName', values.title);
        data.append('EvergrnDescription', values.description);
        data.append('EvergrnCaseEnvironment', getCaseEnvironment());
        data.append('EvergrnSeverity', values.severity.value);
        data.append('EvergrnBrandId', ((_a = values.product) === null || _a === void 0 ? void 0 : _a.value) || brandId);
        data.append('UDPDriveUnityProductId', ConfigService.config.UNITY_PRODUCT_ID);
        return apiMutate(unityUrl, `evergrncase/post-case`, {
            method: 'post',
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }, { data: data });
    }, [unityUrl, uploadedFiles, getCaseEnvironment, brandId]);
    useEffect(() => {
        const fetchData = async () => {
            try {
                if (ConfigService.config.UNITY_PRODUCT_ID === '1') {
                    setUnityState(true);
                }
                else {
                    setUnityState(false);
                }
                let getFileRestrictionsResponse = unityState
                    ? await getFileRestrictionsUnity()
                    : await getFileRestrictions();
                let severityResponse = unityState
                    ? await getSeverityUnity()
                    : await getSeverity();
                let environmentResponse = unityState
                    ? await getEnvironmentUnity()
                    : await getEnvironment();
                if (getFileRestrictionsResponse) {
                    const fileRestrictionsData = getFileRestrictionsResponse.data;
                    setRestrictedFiles(fileRestrictionsData);
                }
                if (severityResponse) {
                    const severityOptions = severityResponse.data.map((item) => ({
                        value: item.externalUUID.toString(),
                        label: item.name
                    }));
                    setSeverityOptions(severityOptions);
                }
                if (environmentResponse) {
                    const environmentOptions = environmentResponse.data.map((item) => ({
                        value: item.evergrnCaseEnvironmentValue.toString(),
                        label: item.evergrnCaseEnvironmentLabel
                    }));
                    setEnvironmentOptions(environmentOptions);
                }
                // fetch brand data
                const brandResponse = await getTenantCaseBrand();
                const tenantSubscribedProductsResponse = await getTenantSubscribedProducts();
                if (brandResponse && tenantSubscribedProductsResponse) {
                    const brandArray = brandResponse.data.filter((brandItem) => brandItem.externalUuid != null);
                    const subscribedArray = tenantSubscribedProductsResponse.data;
                    const brandOptions = subscribedArray
                        .map((subscribedProduct) => {
                        var _a;
                        const foundProduct = brandArray.find((brandItem) => brandItem.productId === subscribedProduct.productId);
                        if (!foundProduct) {
                            return null;
                        }
                        return Object.assign(Object.assign({}, subscribedProduct), { value: (_a = foundProduct.externalUuid) === null || _a === void 0 ? void 0 : _a.toString(), label: foundProduct.name.toString() });
                    })
                        .filter(Boolean);
                    setBrandOptions(brandOptions);
                }
            }
            catch (error) {
                console.error('Error fetching data:', error);
            }
        };
        fetchData();
    }, [
        unityState,
        getSeverityUnity,
        getEnvironmentUnity,
        getFileRestrictionsUnity,
        getFileRestrictions,
        getSeverity,
        getEnvironment,
        getTenantCaseBrand,
        getTenantSubscribedProducts
    ]);
    const handleUploadFile = (files) => {
        const identifiedRestrictedExtensions = [];
        const identifiedRestrictedFileSizes = [];
        files.forEach((file) => {
            const fileExtension = file.name.includes('.')
                ? '.' + file.name.split('.').pop().toLowerCase()
                : '';
            if (restrictedFiles.restrictedExtensions.includes(fileExtension)) {
                identifiedRestrictedExtensions.push(fileExtension);
            }
            if (file.size > restrictedFiles.maxFileSize) {
                identifiedRestrictedFileSizes.push(file.name);
            }
        });
        const isAcceptableExtensions = identifiedRestrictedExtensions.length === 0;
        const isAcceptableSizes = identifiedRestrictedFileSizes.length === 0;
        if (!(isAcceptableExtensions && isAcceptableSizes)) {
            if (!isAcceptableExtensions) {
                const uniqueExtensions = [...new Set(identifiedRestrictedExtensions)];
                const errorText = `Restricted file type(s). ${uniqueExtensions.join(', ')}`;
                enqueueSnackbar(t(errorText), {
                    variant: 'error',
                    anchorOrigin: { vertical: 'top', horizontal: 'center' }
                });
            }
            if (!isAcceptableSizes) {
                const errorText = `File(s) are too large (5MB limit). ${identifiedRestrictedFileSizes.join(', ')}`;
                enqueueSnackbar(t(errorText), {
                    variant: 'error',
                    anchorOrigin: { vertical: 'top', horizontal: 'center' }
                });
            }
            setUploadKey((prevKey) => prevKey + 1);
            return;
        }
        setUploadedFiles(files);
    };
    const handleSubmit = async (values) => {
        var _a;
        setLoadingState(true);
        let response;
        try {
            response = unityState
                ? await postCaseAttachmentUnity(values)
                : await postCaseAttachment(values);
        }
        catch (apiError) {
            console.error('post Case API call failed:', apiError);
            enqueueSnackbar(t('Submission failed'), {
                variant: 'error',
                anchorOrigin: {
                    vertical: 'top',
                    horizontal: 'center'
                },
                action: (key) => (React.createElement(Button, { color: "primary", size: "small", id: "udpRecord-SupportCaseForm-close", onClick: () => {
                        closeSnackbar(key);
                    } }, "clos"))
            });
            setLoadingState(false);
            return { submitError: apiError.message };
        }
        // Check for valid response
        if (!((_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.evergrnCaseId)) {
            console.error('API call succeeded but no case ID returned');
            enqueueSnackbar(t('Submission failed - No case ID returned'), {
                variant: 'error',
                anchorOrigin: {
                    vertical: 'top',
                    horizontal: 'center'
                },
                action: (key) => (React.createElement(Button, { color: "primary", size: "small", id: "udpRecord-SupportCaseForm-close", onClick: () => {
                        closeSnackbar(key);
                    } }, "clos"))
            });
            setLoadingState(false);
            return { submitError: 'No case ID was returned from the server' };
        }
        window.dispatchEvent(new CustomEvent('support-case-created'));
        try {
            handleCloseSupportCaseSideSheet();
        }
        catch (closeError) {
            console.error('Error closing sheet:', closeError);
        }
        enqueueSnackbar(t(`Support Case Created. View your cases`), {
            variant: 'success',
            anchorOrigin: {
                vertical: 'top',
                horizontal: 'center'
            },
            action: (key) => (React.createElement(Button, { color: "primary", size: "small", id: "udpRecord-SupportCaseForm-here", onClick: () => {
                    try {
                        const caseId = response.data.evergrnCaseId;
                        let url;
                        if (unityState) {
                            url = `/support/cases/${caseId}`;
                            history.push(url);
                        }
                        else {
                            url = `${ConfigService.config.UNITY_URL}/support/cases/${caseId}`;
                            window.location.href = url;
                        }
                        closeSnackbar(key);
                    }
                    catch (navError) {
                        console.error('Navigation error:', navError);
                        closeSnackbar(key);
                    }
                } }, "her"))
        });
        try {
            await onSubmit(values);
        }
        catch (onSubmitError) {
            console.error('Error in onSubmit:', onSubmitError);
        }
        setLoadingState(false);
    };
    return (React.createElement(React.Fragment, null, loadingState && React.createElement(LinearProgress, null), React.createElement(Form, { onSubmit: handleSubmit }, React.createElement(AmbientCard, { fullWidth: true }, React.createElement(Field, { component: FluentTextField, name: "title", label: t('Title'), placeholder: t('Enter a brief title for your issue'), variant: "outlined", fullWidth: true, autoFocus: true, required: true }), unityState && (React.createElement(Field, { component: FluentTextFieldAutoComplete, name: "product", label: t('Product'), variant: "outlined", margin: "normal", size: "small", options: brandOptions, optionKey: "label", style: { width: '100%' }, disableClearable: true, id: "udpRecord-CreateSupportCaseForm-product", udprecordid: "udpRecord-CreateSupportCaseForm-product" })), React.createElement(Field, { component: FluentTextFieldAutoComplete, name: "severity", label: t('Severity'), variant: "outlined", margin: "normal", size: "small", options: severityOptions, optionKey: "label", style: { width: '100%' }, disableClearable: true, id: "udpRecord-CreateSupportCaseForm-severity", udprecordid: "udpRecord-CreateSupportCaseForm-severity", required: true })), React.createElement(LayoutUnit, { unit: "xxs" }), React.createElement(AmbientCard, { fullWidth: true }, React.createElement(Field, { name: "description", component: FluentTextField, multiline: true, rows: 10, minRows: 3, maxRows: 20, required: true, label: "Description", placeholder: "Please describe your issue in detail" })), React.createElement(LayoutUnit, { unit: "xxs" }), React.createElement(AmbientCard, { fullWidth: true }, React.createElement(DragDropFileUpload, { key: uploadKey, title: "Attachments", multiple: true, minHeight: "100px", maxHeight: "400px", acceptedFiles: ".pdf,.doc,.docx,.png,.jpg,.jpeg", handleUploadFile: handleUploadFile })), React.createElement(LayoutUnit, { unit: "xxs" }), React.createElement(FormButtons, null, React.createElement(SubmitButton, { color: "primary", variant: "contained", disablePristine: false }, "Submit Ticke")))));
};
export default SupportCaseForm;
//# sourceMappingURL=SupportCaseForm.js.map