import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { QuestionCircleFilled } from '@ant-design/icons';
import { GRANULARITIES } from '@cubejs-client/core';
import { Card, Checkbox, Col, DatePicker, Form, Input, Radio, Row, Select, Space, Tooltip, Typography, } from 'antd';
import { isValidCron } from 'cron-validator';
import { useEffect, useMemo, useState } from 'react';
import styled from 'styled-components';
import { Flex } from '../../grid';
import { ucfirst } from '../../shared/helpers';
import { timeZones } from '../../shared/time-zones';
import { flatten } from '../utils';
const Wrapper = styled.div `
  display: flex;
  gap: 32px;
  flex-direction: column;
  padding: 24px;
`;
const partionGranularities = GRANULARITIES.filter(({ name }) => !['second', 'minute'].includes(name || '')).map((granularity) => {
    if (!granularity.name) {
        return {
            ...granularity,
            title: 'No partition',
        };
    }
    return granularity;
});
export function Settings({ members, hasTimeDimension, onCronExpressionValidityChange, onChange, }) {
    const [form] = Form.useForm();
    const initialValues = {
        refreshKey: {
            checked: {
                every: true,
                sql: false,
            },
            isCron: false,
            sql: '',
            value: 1,
            granularity: 'hour',
            cron: '',
            timeZone: undefined,
        },
        partitionGranularity: '',
        updateWindow: {
            value: 7,
            granularity: 'day',
        },
        incrementalRefresh: true,
        buildRange: {
            since: {
                option: 'relative',
                fixedDate: undefined,
                number: 1,
                granularity: 'year',
                time: 'ago',
            },
            until: {
                option: 'relative',
                fixedDate: undefined,
                number: 1,
                granularity: 'year',
                time: 'from now',
            },
        },
        automatedRefresh: true,
    };
    const flattenedValues = useMemo(() => {
        const values = flatten(initialValues);
        onChange(values);
        return values;
    }, []);
    const [values, setValues] = useState(flattenedValues);
    const [isCron, toggleCron] = useState(false);
    useEffect(() => {
        onChange({ ...values, 'refreshKey.isCron': isCron });
        if (!isCron && !isValidCron(values['refreshKey.cron'])) {
            form.setFields([
                {
                    name: 'refreshKey.cron',
                    value: '',
                    errors: [],
                },
            ]);
        }
    }, [isCron]);
    return (_jsx(Form, { form: form, validateTrigger: "onBlur", initialValues: flatten(initialValues), onValuesChange: (values) => {
            setValues((prevValues) => {
                onChange({ ...prevValues, ...values, 'refreshKey.isCron': isCron });
                Object.keys(values).forEach((field) => {
                    const error = form.getFieldError(field);
                    if (!error.length) {
                        return;
                    }
                    form.setFields([
                        {
                            name: field,
                            errors: [],
                        },
                    ]);
                });
                return { ...prevValues, ...values };
            });
        }, children: _jsxs(Wrapper, { children: [_jsxs(Card, { children: [_jsx(TitleWithTooltip, { title: "Refresh Key", children: "Specify how often to refresh your pre-aggregated data" }), _jsx(Typography.Paragraph, { children: "If you do not specify any Refresh Key, refreshes will still default to every 1 hour." }), _jsxs(Row, { gutter: 8, wrap: false, align: "top", children: [_jsx(Col, { flex: "85px", children: _jsx(Form.Item, { name: "refreshKey.checked.every", valuePropName: "checked", children: _jsx(Checkbox, { children: "Every" }) }) }), _jsx(Col, { flex: "auto", children: _jsxs(Flex, { direction: "column", gap: 2, children: [_jsxs(Space, { children: [_jsx(Radio, { checked: !isCron, disabled: !values['refreshKey.checked.every'], onClick: () => toggleCron(false) }), _jsx(Form.Item, { name: "refreshKey.value", noStyle: true, children: _jsx(Input, { "data-testid": "rd-input-every", disabled: !values['refreshKey.checked.every'] || isCron, type: "number", min: 0, style: { maxWidth: 80 } }) }), _jsx(Form.Item, { name: "refreshKey.granularity", noStyle: true, children: _jsx(GranularitySelect, { "data-testid": "rd-select-every-granularity", disabled: !values['refreshKey.checked.every'] || isCron, excludedGranularities: ['year', 'quarter', 'month'] }) })] }), _jsxs(Space, { align: "start", style: { marginBottom: 32 }, children: [_jsx(Radio, { disabled: !values['refreshKey.checked.every'], checked: isCron, style: { paddingTop: 5 }, onClick: () => toggleCron(true) }), _jsxs(Flex, { direction: "column", gap: 1, children: [_jsx(Form.Item, { name: "refreshKey.cron", rules: [
                                                                    {
                                                                        validator: (_, value, callback) => {
                                                                            if (value &&
                                                                                !isValidCron(value, { seconds: true })) {
                                                                                onCronExpressionValidityChange(false);
                                                                                callback('Cron expression is invalid');
                                                                            }
                                                                            else {
                                                                                onCronExpressionValidityChange(true);
                                                                            }
                                                                        },
                                                                    },
                                                                ], children: _jsx(Input, { allowClear: true, placeholder: "Cron expression e.g. 30 5 * * 5", disabled: !values['refreshKey.checked.every'] || !isCron }) }), isCron && values['refreshKey.checked.every'] ? (_jsxs(_Fragment, { children: [_jsx(Typography.Paragraph, { children: _jsx(Typography.Link, { target: "_blank", href: "https://cube.dev/docs/schema/reference/cube#supported-cron-formats", children: "See how to format your cron expression" }) }), _jsx(Typography.Paragraph, { strong: true, children: "Time Zone" }), _jsx(Form.Item, { name: "refreshKey.timeZone", noStyle: true, children: _jsx(Select, { showSearch: true, style: { maxWidth: 200 }, placeholder: "Select Time Zone", children: timeZones.map((name) => (_jsx(Select.Option, { value: name || '', children: name }, name))) }) })] })) : null] })] })] }) })] }), _jsxs(Row, { gutter: 8, children: [_jsx(Col, { flex: "85px", children: _jsx(Form.Item, { name: "refreshKey.checked.sql", valuePropName: "checked", noStyle: true, children: _jsx(Checkbox, { children: "SQL" }) }) }), _jsx(Col, { flex: "auto", children: _jsx(Form.Item, { name: "refreshKey.sql", noStyle: true, children: _jsx(Input.TextArea, { disabled: !values['refreshKey.checked.sql'], placeholder: "SELECT MAX(createdAt) FROM orders" }) }) })] })] }), _jsxs(Card, { children: [hasTimeDimension ? (_jsxs(_Fragment, { children: [_jsx(TitleWithTooltip, { title: "Partition Granularity", children: "Partitions are shards of the pre-aggregation dataset. To enable partitions, you must specify here the desired granularity." }), _jsx(Form.Item, { name: "partitionGranularity", children: _jsx(Select, { showSearch: true, style: { maxWidth: 150 }, children: partionGranularities.map(({ name, title }) => (_jsx(Select.Option, { value: name || '', children: title }, name))) }) }), values.partitionGranularity ? (_jsxs(_Fragment, { children: [_jsx(Form.Item, { name: "incrementalRefresh", valuePropName: "checked", children: _jsx(Checkbox, { children: "Incremental Refresh" }) }), values['incrementalRefresh'] && (_jsxs(_Fragment, { children: [_jsx(TitleWithTooltip, { title: "Update Window", children: "Any partition which includes this span of time into the past from now will be refreshed according to the Refresh Key set above. Otherwise, if left unset, only the most recent partition will be refreshed regularly." }), _jsxs(Space, { align: "start", children: [_jsx(Form.Item, { name: "updateWindow.value", children: _jsx(Input, { type: "number", min: 0, style: { maxWidth: 80 } }) }), _jsx(Form.Item, { name: "updateWindow.granularity", children: _jsx(GranularitySelect, { excludedGranularities: ['second'] }) })] })] }))] })) : null] })) : null, _jsx(Typography.Paragraph, { strong: true, children: "Indexes" }), _jsx(Form.Item, { name: "indexes", noStyle: true, children: _jsx(Select, { mode: "tags", style: { width: '100%' }, placeholder: "(list column names)", children: members.map((name) => (_jsx(Select.Option, { value: name, children: name }, name))) }) })] })] }) }));
}
function BuildRange({ time }) {
    const name = (key) => `buildRange.${time}.${key}`;
    return (_jsxs(Row, { children: [_jsx(Col, { flex: "60px", children: ucfirst(time) }), _jsx(Col, { flex: "auto", children: _jsx(Form.Item, { name: `buildRange.${time}.option`, noStyle: true, children: _jsx(Radio.Group, { children: _jsxs(Flex, { direction: "column", gap: 2, children: [_jsxs(Space, { children: [_jsx(Radio, { value: "relative" }), _jsx(Form.Item, { name: name('number'), noStyle: true, children: _jsx(Input, { type: "number", min: 0, style: { maxWidth: 80 } }) }), _jsx(Form.Item, { name: name('granularity'), noStyle: true, children: _jsx(GranularitySelect, {}) })] }), _jsxs(Space, { children: [_jsx(Radio, { value: "fixed" }), _jsx(Form.Item, { name: name('fixedDate'), noStyle: true, children: _jsx(DatePicker, { placeholder: "Fixed date", style: { width: '100%' } }) })] }), _jsx(Radio, { value: "now", children: "Now" })] }) }) }) })] }));
}
export function GranularitySelect({ excludedGranularities = [], ...props }) {
    return (_jsx(Select, { style: { minWidth: 100 }, showSearch: true, ...props, children: GRANULARITIES.filter(({ name }) => name != null && !excludedGranularities.includes(name)).map(({ name, title }) => (_jsx(Select.Option, { value: name, children: title }, name))) }));
}
function TitleWithTooltip({ title, children }) {
    return (_jsxs(Space, { align: "baseline", style: {
            display: 'flex',
        }, children: [_jsx(Typography.Paragraph, { strong: true, children: title }), _jsx(Tooltip, { title: children, children: _jsx(QuestionCircleFilled, { style: { color: '#1414464D' } }) })] }));
}
//# sourceMappingURL=Settings.js.map