// (C) 2022-2026 GoodData Corporation
import { useCallback, useState } from "react";
import { areObjRefsEqual, isExportDefinitionDashboardRequestPayload, isExportDefinitionVisualizationObjectRequestPayload, isInsightWidget, } from "@gooddata/sdk-model";
import { useToastMessage } from "@gooddata/sdk-ui-kit";
import { messages } from "../../../locales.js";
import { selectEnableAutomationManagement } from "../../store/config/configSelectors.js";
import { selectInsights } from "../../store/insights/insightsSelectors.js";
import { selectDashboardRef } from "../../store/meta/metaSelectors.js";
import { selectNotificationChannels } from "../../store/notificationChannels/notificationChannelsSelectors.js";
import { selectWidgets } from "../../store/tabs/layout/layoutSelectors.js";
import { useDashboardSelector } from "../DashboardStoreProvider.js";
import { useDashboardAutomations } from "../useDashboardAutomations/useDashboardAutomations.js";
import { useDashboardUserInteraction } from "../useDashboardUserInteraction.js";
import { useDashboardScheduledEmailsCommands } from "./useDashboardScheduledEmailsCommands.js";
/**
 * @internal
 */
export const useDashboardScheduledEmailsDialog = () => {
    const { addSuccess, addError } = useToastMessage();
    const { automationInteraction } = useDashboardUserInteraction();
    const dashboardRef = useDashboardSelector(selectDashboardRef);
    const destinations = useDashboardSelector(selectNotificationChannels);
    const allWidgets = useDashboardSelector(selectWidgets);
    const allInsights = useDashboardSelector(selectInsights);
    const enableAutomationManagement = useDashboardSelector(selectEnableAutomationManagement);
    const { closeScheduleEmailingDialog, openScheduleEmailingDialog, openScheduleEmailingManagementDialog } = useDashboardScheduledEmailsCommands();
    const { refreshAutomations, refreshAutomationManagementItems } = useDashboardAutomations();
    const [shouldReturnToManagementDialog, setShouldReturnToManagementDialog] = useState(false);
    const handleRefreshAutomations = useCallback(() => {
        if (enableAutomationManagement) {
            refreshAutomationManagementItems();
        }
        else {
            refreshAutomations();
        }
    }, [enableAutomationManagement, refreshAutomations, refreshAutomationManagementItems]);
    /*
     * exports and scheduling are not available when rendering a dashboard that is not persisted.
     * this can happen when a new dashboard is created and is being edited.
     *
     * the setup of menu items available in the menu needs to reflect this.
     */
    const defaultOnScheduleEmailing = useCallback((widget) => {
        if (!dashboardRef) {
            return;
        }
        openScheduleEmailingDialog({ widget, openedFrom: "dashboard" });
        setShouldReturnToManagementDialog(false);
    }, [dashboardRef, openScheduleEmailingDialog, setShouldReturnToManagementDialog]);
    // Open / Close
    const onScheduleEmailingOpen = useCallback((widget) => {
        openScheduleEmailingDialog({ widget, openedFrom: "widget" });
        setShouldReturnToManagementDialog(false);
    }, [openScheduleEmailingDialog, setShouldReturnToManagementDialog]);
    const onScheduleEmailingCancel = useCallback((widget) => {
        closeScheduleEmailingDialog();
        if (!enableAutomationManagement && shouldReturnToManagementDialog) {
            openScheduleEmailingManagementDialog(widget);
        }
    }, [
        enableAutomationManagement,
        shouldReturnToManagementDialog,
        closeScheduleEmailingDialog,
        openScheduleEmailingManagementDialog,
    ]);
    const onScheduleEmailingBack = useCallback((widget) => {
        closeScheduleEmailingDialog();
        if (!enableAutomationManagement) {
            openScheduleEmailingManagementDialog(widget);
        }
    }, [enableAutomationManagement, closeScheduleEmailingDialog, openScheduleEmailingManagementDialog]);
    // Create
    const onScheduleEmailingCreateSuccess = useCallback((scheduledEmail) => {
        closeScheduleEmailingDialog();
        if (!enableAutomationManagement) {
            openScheduleEmailingManagementDialog();
        }
        addSuccess(messages.scheduleEmailSubmitSuccess);
        handleRefreshAutomations();
        const widgetId = scheduledEmail.exportDefinitions?.find(({ requestPayload }) => isExportDefinitionVisualizationObjectRequestPayload(requestPayload))?.requestPayload?.content.widget;
        const widget = allWidgets.find((widget) => widget.localIdentifier === widgetId);
        const insight = allInsights.find((insight) => {
            return isInsightWidget(widget) && areObjRefsEqual(insight.insight.ref, widget.insight);
        });
        const dashboardFilters = scheduledEmail.exportDefinitions?.find(({ requestPayload }) => isExportDefinitionDashboardRequestPayload(requestPayload))?.requestPayload.content.filters ?? [];
        const destinationType = destinations.find((channel) => channel.id === scheduledEmail.notificationChannel)?.destinationType;
        automationInteraction({
            type: "scheduledExportCreated",
            destination_id: scheduledEmail.notificationChannel,
            destination_type: destinationType,
            automation_id: scheduledEmail.id,
            automation_name: scheduledEmail.title,
            automation_source: widgetId ? "widget" : "dashboard",
            ...(insight ? { automation_visualization_type: insight?.insight.visualizationUrl } : {}),
            ...(insight ? {} : { filter_context: dashboardFilters.length > 0 ? "edited" : "default" }),
        });
    }, [
        enableAutomationManagement,
        closeScheduleEmailingDialog,
        openScheduleEmailingManagementDialog,
        addSuccess,
        handleRefreshAutomations,
        allWidgets,
        allInsights,
        destinations,
        automationInteraction,
    ]);
    const onScheduleEmailingCreateError = useCallback(() => {
        closeScheduleEmailingDialog();
        addError(messages.scheduleEmailSubmitError);
    }, [closeScheduleEmailingDialog, addError]);
    // Edit
    const onScheduleEmailingSaveSuccess = useCallback((widget) => {
        closeScheduleEmailingDialog();
        if (!enableAutomationManagement) {
            openScheduleEmailingManagementDialog(widget);
        }
        addSuccess(messages.scheduleEmailSaveSuccess);
        handleRefreshAutomations();
    }, [
        enableAutomationManagement,
        closeScheduleEmailingDialog,
        openScheduleEmailingManagementDialog,
        addSuccess,
        handleRefreshAutomations,
    ]);
    const onScheduleEmailingSaveError = useCallback(() => {
        closeScheduleEmailingDialog();
        addError(messages.scheduleEmailSaveError);
    }, [closeScheduleEmailingDialog, addError]);
    return {
        defaultOnScheduleEmailing,
        onScheduleEmailingOpen,
        onScheduleEmailingCancel,
        onScheduleEmailingBack,
        onScheduleEmailingCreateError,
        onScheduleEmailingCreateSuccess,
        onScheduleEmailingSaveError,
        onScheduleEmailingSaveSuccess,
        setShouldReturnToManagementDialog,
    };
};
