import { useState, useEffect, useCallback, useContext, useRef } from 'react';
import { getAssigneeForTask, updateAssigneeForTask, utils } from '@reltio/mdm-sdk';
import { useSafePromise } from '../../../hooks/useSafePromise';
import { WorkflowTasksContext } from '../../../contexts/WorkflowTasksContext';
import { useMdmTenant, useMdmWorkflowEnvironmentUrl, useMdmWorkflowPath } from '../../../contexts/MdmModuleContext';
import { showWorkflowError } from '../helpers/errors';
import { useWorkflowCheckPermission } from './useWorkflowCheckPermission';
import { isOpenTask } from '../helpers/common';
var assigneeToValue = function (assignee) { return ({
    label: assignee,
    value: assignee
}); };
var filterAssignees = function (assignees, text) {
    return assignees.filter(function (item) { return item.value.toLowerCase().includes(text === null || text === void 0 ? void 0 : text.toLowerCase()); });
};
export var useWorkflowAssignee = function (_a) {
    var assignee = _a.assignee, _b = _a.showCurrentAssignee, showCurrentAssignee = _b === void 0 ? true : _b, taskId = _a.taskId, isOpen = _a.isOpen, onChange = _a.onChange;
    var updateTaskState = (useContext(WorkflowTasksContext) || {}).updateTaskState;
    var workflowPath = useMdmWorkflowPath();
    var environment = useMdmWorkflowEnvironmentUrl();
    var tenant = useMdmTenant();
    var updateSafePromise = useSafePromise();
    var _c = useState(null), currentAssignee = _c[0], setCurrentAssignee = _c[1];
    var _d = useState(false), updateRequestIsInProgress = _d[0], setUpdateRequestIsInProgress = _d[1];
    var checkWorkflowPermission = useWorkflowCheckPermission();
    var canUpdateTask = checkWorkflowPermission('UPDATE_TASK') && isOpenTask(isOpen);
    var assigneesRequestRef = useRef(null);
    useEffect(function () {
        if (showCurrentAssignee)
            setCurrentAssignee(assigneeToValue(assignee));
    }, 
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [assignee]);
    var getAssignees = useCallback(function (text) {
        if (workflowPath && canUpdateTask && taskId) {
            if (!assigneesRequestRef.current) {
                assigneesRequestRef.current = getAssigneeForTask({
                    taskId: taskId,
                    workflowPath: workflowPath,
                    environment: environment,
                    tenant: tenant
                });
            }
            return assigneesRequestRef.current
                .then(function (result) {
                var data = result.data;
                var fetchedAssignees = data
                    .filter(function (a) { return (showCurrentAssignee ? true : a !== assignee); })
                    .sort(function (a, b) { return utils.strings.sort('asc', a, b); })
                    .map(assigneeToValue);
                return filterAssignees(fetchedAssignees, text);
            })
                .catch(function (e) {
                showWorkflowError(e);
                assigneesRequestRef.current = null;
            });
        }
    }, [workflowPath, taskId, environment, tenant, canUpdateTask, assignee, showCurrentAssignee]);
    var updateAssignee = useCallback(function (newValue) {
        var assignee = newValue.value;
        if (onChange) {
            setCurrentAssignee(assigneeToValue(assignee));
            onChange(assignee);
        }
        if (!onChange && workflowPath && canUpdateTask && taskId) {
            setUpdateRequestIsInProgress(true);
            updateSafePromise(updateAssigneeForTask({
                taskId: taskId,
                workflowPath: workflowPath,
                environment: environment,
                tenant: tenant,
                assignee: assignee
            }))
                .then(function () {
                setCurrentAssignee(assigneeToValue(assignee));
                updateTaskState === null || updateTaskState === void 0 ? void 0 : updateTaskState(taskId, { assignee: assignee });
            })
                .catch(showWorkflowError)
                .finally(function () {
                setUpdateRequestIsInProgress(false);
            });
        }
    }, 
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [workflowPath, taskId, environment, tenant, canUpdateTask, onChange]);
    return {
        assignee: currentAssignee,
        getAssignees: getAssignees,
        updateAssignee: updateAssignee,
        updateRequestIsInProgress: updateRequestIsInProgress,
        readOnly: !canUpdateTask
    };
};
