import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2025-2026 GoodData Corporation
import { useId, useMemo, useState } from "react";
import { FormattedMessage, useIntl } from "react-intl";
import { DEFAULT_CSV_DELIMITER, getCsvDelimiterState, getCsvDelimiterValidationError, getCsvDelimiterValue, } from "@gooddata/sdk-model";
import { Button, ContentDivider, CsvDelimiterPicker, Dropdown, DropdownButton, UiIcon, UiMenu, isEscapeKey, } from "@gooddata/sdk-ui-kit";
import { AUTOMATION_ATTACHMENT_SETTINGS_DIALOG_TITLE_ID } from "../../../../../constants/automations.js";
const DROPDOWN_ALIGN_POINTS = [
    {
        align: "bc tc",
        offset: { x: 0, y: 0 },
    },
    {
        align: "tc bc",
        offset: { x: 0, y: 0 },
    },
];
const OVERLAY_POSITION_TYPE = "sameAsTarget";
const CLOSE_ON_PARENT_SCROLL = true;
const DEFAULT_PDF_PAGE_SIZE = "A4";
const DEFAULT_PDF_PAGE_ORIENTATION = "PORTRAIT";
const DEFAULT_PDF_ORIENTATION = "portrait";
const mapLegacyOrientationToPageOrientation = (orientation) => {
    if (orientation === "portrait") {
        return "PORTRAIT";
    }
    if (orientation === "landscape") {
        return "LANDSCAPE";
    }
    return undefined;
};
const mapPageOrientationToLegacyOrientation = (orientation) => {
    if (orientation === "LANDSCAPE") {
        return "landscape";
    }
    if (orientation === "PORTRAIT") {
        return "portrait";
    }
    return undefined;
};
export function AttachmentSettings({ type, settings, onSettingsChange, defaultPdfPageSize, }) {
    const intl = useIntl();
    const isPdfTabular = type === "PDF_TABULAR";
    const isCsv = type === "CSV" || type === "CSV_RAW";
    const legacyOrientation = settings.orientation;
    const legacyPageOrientation = mapLegacyOrientationToPageOrientation(legacyOrientation);
    const resolvedDefaultPageSize = settings.pageSize ?? defaultPdfPageSize ?? DEFAULT_PDF_PAGE_SIZE;
    const resolvedCsvDelimiter = settings.delimiter ?? DEFAULT_CSV_DELIMITER;
    const resolvedCsvState = getCsvDelimiterState(settings.delimiter);
    const [mergeHeaders, setMergeHeaders] = useState(settings.mergeHeaders ?? true);
    const [exportInfo, setExportInfo] = useState(settings.exportInfo ?? true);
    const [pageSize, setPageSize] = useState(resolvedDefaultPageSize);
    const [pageOrientation, setPageOrientation] = useState(legacyPageOrientation ?? DEFAULT_PDF_PAGE_ORIENTATION);
    const [csvDelimiterValue, setCsvDelimiterValue] = useState(resolvedCsvState);
    const pageSizeMenuId = useId();
    const orientationMenuId = useId();
    const settingsLabel = isPdfTabular
        ? intl.formatMessage({ id: "dialogs.export.pdf.headline" })
        : isCsv
            ? intl.formatMessage({
                id: "dialogs.schedule.management.attachments.csv.settings",
                defaultMessage: "CSV options",
            })
            : intl.formatMessage({ id: "dialogs.schedule.management.attachments.xlsx.settings" });
    const pageSizeMenuItems = useMemo(() => [
        {
            type: "interactive",
            id: "A3",
            stringTitle: intl.formatMessage({ id: "dialogs.export.pdf.pageSize.option.a3" }),
            data: "A3",
        },
        {
            type: "interactive",
            id: "A4",
            stringTitle: intl.formatMessage({ id: "dialogs.export.pdf.pageSize.option.a4" }),
            data: "A4",
        },
        {
            type: "interactive",
            id: "Letter",
            stringTitle: intl.formatMessage({ id: "dialogs.export.pdf.pageSize.option.letter" }),
            data: "LETTER",
        },
    ], [intl]);
    const orientationMenuItems = useMemo(() => [
        {
            type: "interactive",
            id: "Portrait",
            stringTitle: intl.formatMessage({ id: "dialogs.export.pdf.pageOrientation.option.portrait" }),
            data: "PORTRAIT",
        },
        {
            type: "interactive",
            id: "Landscape",
            stringTitle: intl.formatMessage({
                id: "dialogs.export.pdf.pageOrientation.option.landscape",
            }),
            data: "LANDSCAPE",
        },
    ], [intl]);
    const resetSettings = () => {
        const nextCsvState = getCsvDelimiterState(settings.delimiter);
        setMergeHeaders(settings.mergeHeaders ?? true);
        setExportInfo(settings.exportInfo ?? true);
        setPageSize(resolvedDefaultPageSize);
        setPageOrientation(legacyPageOrientation ?? DEFAULT_PDF_PAGE_ORIENTATION);
        setCsvDelimiterValue(nextCsvState);
    };
    const isPdfSettingsDirty = pageSize !== resolvedDefaultPageSize ||
        (mapPageOrientationToLegacyOrientation(pageOrientation) ?? DEFAULT_PDF_ORIENTATION) !==
            (legacyOrientation ?? DEFAULT_PDF_ORIENTATION) ||
        exportInfo !== (settings.exportInfo ?? true);
    const isXlsxSettingsDirty = mergeHeaders !== (settings.mergeHeaders ?? true) || exportInfo !== (settings.exportInfo ?? true);
    const selectedDelimiter = getCsvDelimiterValue(csvDelimiterValue.selectedPreset, csvDelimiterValue.customDelimiter);
    const csvValidationError = csvDelimiterValue.selectedPreset === "custom"
        ? getCsvDelimiterValidationError(csvDelimiterValue.customDelimiter)
        : undefined;
    const isCsvSettingsDirty = selectedDelimiter !== resolvedCsvDelimiter;
    const isSettingsDirty = isPdfTabular
        ? isPdfSettingsDirty
        : isCsv
            ? isCsvSettingsDirty
            : isXlsxSettingsDirty;
    const isSaveDisabled = !isSettingsDirty ||
        (isCsv &&
            (csvDelimiterValue.selectedPreset === "custom"
                ? !csvDelimiterValue.customDelimiter || Boolean(csvValidationError)
                : false));
    return (_jsx(Dropdown, { closeOnParentScroll: CLOSE_ON_PARENT_SCROLL, overlayPositionType: OVERLAY_POSITION_TYPE, alignPoints: DROPDOWN_ALIGN_POINTS, autofocusOnOpen: true, onOpenStateChanged: (isOpen) => {
            if (!isOpen) {
                resetSettings();
            }
        }, renderButton: ({ toggleDropdown, buttonRef }) => (_jsx("button", { className: "gd-attachment-chip-button", onClick: toggleDropdown, ref: buttonRef, "aria-label": settingsLabel, children: _jsx(UiIcon, { type: "settings", size: 14, color: "complementary-8" }) })), renderBody: ({ closeDropdown }) => (_jsxs("div", { className: `gd-attachment-settings-dropdown${isCsv ? " gd-attachment-settings-dropdown--csv" : ""}`, role: "dialog", "aria-labelledby": AUTOMATION_ATTACHMENT_SETTINGS_DIALOG_TITLE_ID, onKeyDown: (e) => {
                if (isEscapeKey(e)) {
                    e.stopPropagation();
                    closeDropdown();
                }
            }, children: [
                _jsx("h3", { className: "gd-list-title", id: AUTOMATION_ATTACHMENT_SETTINGS_DIALOG_TITLE_ID, children: settingsLabel }), _jsx("span", { className: "gd-close-button", children: _jsx(Button, { className: "gd-button-link gd-button-icon-only gd-icon-cross s-dialog-close-button", value: "", onClick: closeDropdown, accessibilityConfig: {
                            ariaLabel: intl.formatMessage({ id: "close" }),
                            ariaDescribedBy: AUTOMATION_ATTACHMENT_SETTINGS_DIALOG_TITLE_ID,
                        } }) }), _jsx("div", { className: "gd-attachment-settings-dropdown-content", children: isPdfTabular ? (_jsxs(_Fragment, { children: [
                            _jsxs("div", { className: "gd-pdf-export-dialog-item", children: [
                                    _jsx("h4", { children: _jsx(FormattedMessage, { id: "dialogs.export.pdf.pageSize" }) }), _jsx(Dropdown, { fullscreenOnMobile: false, renderButton: ({ isOpen, toggleDropdown }) => (_jsx(DropdownButton, { value: pageSizeMenuItems.find((item) => item.data === pageSize)
                                                ?.stringTitle, isOpen: isOpen, onClick: toggleDropdown, accessibilityConfig: {
                                                ariaLabel: intl.formatMessage({
                                                    id: "dialogs.export.pdf.pageSize",
                                                }),
                                                ariaHaspopup: "true",
                                                ariaExpanded: isOpen,
                                                ...(isOpen
                                                    ? {
                                                        ariaControls: `pdf-page-size-menu-${pageSizeMenuId}`,
                                                    }
                                                    : {}),
                                            }, isFullWidth: true })), renderBody: ({ closeDropdown: closePageSizeDropdown }) => (_jsx(UiMenu, { items: pageSizeMenuItems.map((item) => ({
                                                ...item,
                                                isSelected: pageSize === item.data,
                                            })), onSelect: (item) => {
                                                setPageSize(item.data);
                                            }, onClose: closePageSizeDropdown, shouldCloseOnSelect: true, ariaAttributes: {
                                                "aria-label": intl.formatMessage({
                                                    id: "dialogs.export.pdf.pageSize",
                                                }),
                                                id: `pdf-page-size-menu-${pageSizeMenuId}`,
                                            }, maxWidth: 150 })), autofocusOnOpen: true })] }), _jsxs("div", { className: "gd-pdf-export-dialog-item", children: [
                                    _jsx("h4", { children: _jsx(FormattedMessage, { id: "dialogs.export.pdf.pageOrientation" }) }), _jsx(Dropdown, { fullscreenOnMobile: false, renderButton: ({ isOpen, toggleDropdown }) => (_jsx(DropdownButton, { value: orientationMenuItems.find((item) => item.data === pageOrientation)?.stringTitle, isOpen: isOpen, onClick: toggleDropdown, accessibilityConfig: {
                                                ariaLabel: intl.formatMessage({
                                                    id: "dialogs.export.pdf.pageOrientation",
                                                }),
                                                ariaHaspopup: "true",
                                                ariaExpanded: isOpen,
                                                ...(isOpen
                                                    ? {
                                                        ariaControls: `pdf-orientation-menu-${orientationMenuId}`,
                                                    }
                                                    : {}),
                                            }, isFullWidth: true })), renderBody: ({ closeDropdown: closeOrientationDropdown }) => (_jsx(UiMenu, { items: orientationMenuItems.map((item) => ({
                                                ...item,
                                                isSelected: pageOrientation === item.data,
                                            })), onSelect: (item) => {
                                                setPageOrientation(item.data);
                                            }, onClose: closeOrientationDropdown, shouldCloseOnSelect: true, ariaAttributes: {
                                                "aria-label": intl.formatMessage({
                                                    id: "dialogs.export.pdf.pageOrientation",
                                                }),
                                                id: `pdf-orientation-menu-${orientationMenuId}`,
                                            }, maxWidth: 150 })), autofocusOnOpen: true })] }), _jsxs("label", { className: "input-checkbox-label", children: [
                                    _jsx("input", { type: "checkbox", className: "input-checkbox", onChange: () => setExportInfo(!exportInfo), checked: exportInfo }), _jsx("span", { className: "input-label-text", children: _jsx(FormattedMessage, { id: "dialogs.export.pdf.includePageExportInfo" }) })
                                ] })
                        ] })) : isCsv ? (_jsx("div", { className: "gd-attachment-settings-dropdown-item", children: _jsx(CsvDelimiterPicker, { value: csvDelimiterValue, onChange: setCsvDelimiterValue, validationError: csvValidationError, label: intl.formatMessage({
                                id: "dialogs.export.csv.delimiter",
                                defaultMessage: "CSV delimiter",
                            }), onEnterKeyPress: isSaveDisabled
                                ? undefined
                                : () => {
                                    onSettingsChange({
                                        ...settings,
                                        delimiter: selectedDelimiter,
                                    });
                                    closeDropdown();
                                } }) })) : (_jsxs(_Fragment, { children: [
                            _jsxs("label", { className: "input-checkbox-label", children: [
                                    _jsx("input", { type: "checkbox", className: "input-checkbox", onChange: () => setMergeHeaders(!mergeHeaders), checked: mergeHeaders }), _jsx("span", { className: "input-label-text", children: _jsx(FormattedMessage, { id: "dialogs.schedule.management.attachments.cells.merged" }) })
                                ] }), _jsxs("label", { className: "input-checkbox-label", children: [
                                    _jsx("input", { type: "checkbox", className: "input-checkbox", onChange: () => setExportInfo(!exportInfo), checked: exportInfo }), _jsx("span", { className: "input-label-text", children: _jsx(FormattedMessage, { id: "dialogs.schedule.management.attachments.exportInfo" }) })
                                ] })
                        ] })) }), _jsx(ContentDivider, { className: "gd-divider-without-margin" }), _jsxs("div", { className: "gd-attachment-settings-dropdown-footer", children: [
                        _jsx(Button, { value: intl.formatMessage({ id: "cancel" }), className: "gd-button-secondary", onClick: closeDropdown }), _jsx(Button, { value: intl.formatMessage({ id: "save" }), className: "gd-button-action", onClick: () => {
                                if (isPdfTabular) {
                                    onSettingsChange({
                                        pageSize,
                                        exportInfo,
                                        orientation: mapPageOrientationToLegacyOrientation(pageOrientation) ??
                                            DEFAULT_PDF_ORIENTATION,
                                    });
                                }
                                else if (isCsv) {
                                    onSettingsChange({
                                        ...settings,
                                        delimiter: selectedDelimiter,
                                    });
                                }
                                else {
                                    onSettingsChange({
                                        mergeHeaders,
                                        exportInfo,
                                    });
                                }
                                closeDropdown();
                            }, disabled: isSaveDisabled })
                    ] })
            ] })) }));
}
