import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { forwardRef, useEffect, useState } from 'react';
import styled, { css } from 'styled-components';
import Icon, { registerIcon } from '../Icon';
import * as openIcon from '../Icon/icons/open.icon';
import * as timesIcon from '../Icon/icons/times.icon';
import * as previewIcon from '../Icon/icons/preview.icon';
import * as editIcon from '../Icon/icons/pencil.icon';
import * as downloadIcon from '../Icon/icons/download.icon';
import * as deleteIcon from '../Icon/icons/trash.icon';
import Text, { StyledText } from '../Text';
import Tooltip from '../Tooltip';
import { defaultThemeProp } from '../../theme';
import Button, { StyledButton } from '../Button';
import { useI18n, useElement, useConfiguration, useConsolidatedRef } from '../../hooks';
import Actions from '../Actions';
import Progress from '../Progress';
import { StyledProgressRing } from '../Progress/Progress.styles';
import { formatNumber } from '../Number';
import Flex from '../Flex';
import { StyledIconShape } from '../Icon/Icon';
import { getActiveElement, getFocusables } from '../../utils';
import { ellipsisOverflow } from '../../styles/mixins';
import { getKindFromMimeType, getMimeTypeFromFile } from './utils';
import FileVisual, { StyledFileVisual } from './FileVisual';
registerIcon(openIcon, timesIcon, previewIcon, editIcon, downloadIcon, deleteIcon);
const StyledErrorIcon = styled(Icon)(({ theme }) => {
    return css `
    color: ${theme.base.palette.urgent};
    margin-inline-start: calc(0.5 * ${theme.base.spacing});
  `;
});
StyledErrorIcon.defaultProps = defaultThemeProp;
const titleEllipsisStyle = css `
  flex-shrink: 1;
  ${ellipsisOverflow}
`;
const StyledPreviewTitle = styled(Button) `
  ${titleEllipsisStyle}
`;
const StyledTextTitle = styled(Text) `
  ${titleEllipsisStyle}
`;
const StyledMeta = styled(StyledText)(({ theme, error }) => {
    return css `
    /* min width to show percentage in full */
    min-width: 4ch;
    margin-inline-start: auto;
    ${titleEllipsisStyle}
    ${error &&
        css `
      color: ${theme.base.palette.urgent};
    `}
  `;
});
StyledMeta.defaultProps = defaultThemeProp;
const StyledActionsWrapper = styled.div(({ meta }) => {
    return css `
    margin-inline-start: ${meta ? 'unset' : 'auto'};
  `;
});
StyledActionsWrapper.defaultProps = defaultThemeProp;
export const StyledFileItem = styled.div(({ theme: { base: { palette, 'border-radius': borderRadius, spacing, 'hit-area': { compact }, 'disabled-opacity': disabledOpacity }, components: { input, 'form-control': { ':disabled': { 'background-color': disabledBackgroundColor, 'border-color': disabledBorderColor }, 'border-radius': formBorderRadius } } }, compactMode, isDisabled }) => {
    return css `
      border-radius: calc(${borderRadius} * ${formBorderRadius});
      border: 0.0625rem solid ${palette['border-line']};
      background-color: ${palette['primary-background']};
      height: ${input.height};
      min-width: calc(${input.height} + 12ch + 1.5 * ${spacing} + ${compact});

      ${compactMode &&
        css `
        height: ${compact};
        min-width: calc(${compact} + 12ch + 2 * ${spacing});
        width: fit-content;
        max-width: 25ch;

        ${StyledPreviewTitle}, ${StyledTextTitle} {
          min-width: 12ch;
          max-width: calc(25ch - (${compact} + 2 * ${spacing}));
        }

        ${StyledActionsWrapper} > ${StyledButton} {
          min-height: 100%;
          min-width: 100%;
          margin-block: ${spacing};
        }
      `}

      > ${StyledProgressRing} {
        margin-inline-start: calc(0.5 * ${spacing});
      }

      > ${StyledFileVisual}, > ${StyledIconShape} {
        border-start-start-radius: inherit;
        border-end-start-radius: inherit;
        border-start-end-radius: 0;
        border-end-end-radius: 0;
        width: ${input.height};
        flex-shrink: 0;

        ${compactMode &&
        css `
          height: ${compact};
          width: ${compact};
        `}
      }
      ${isDisabled &&
        css `
        background-color: ${disabledBackgroundColor};
        border-color: ${disabledBorderColor};
        opacity: ${disabledOpacity};
      `}
    `;
});
StyledFileItem.defaultProps = defaultThemeProp;
const FileItem = forwardRef(function FileItem(props, ref) {
    const { id, name, thumbnail, format, error, onCancel, onEdit, onPreview, onDownload, onDelete, onOpen, progress, compact = false, previewFromActions = false, disabled = false, ...restProps } = props;
    const [thumbnailError, setThumbnailError] = useState(false);
    const [textTarget, setTextTarget] = useElement();
    const [metaTarget, setMetaTarget] = useElement();
    const { locale } = useConfiguration();
    const t = useI18n();
    const uploading = typeof progress === 'number' && progress < 100;
    const itemRef = useConsolidatedRef(ref);
    const activeElement = getActiveElement();
    const activeElementInItem = itemRef.current?.contains(activeElement);
    let metaMessage;
    if (uploading) {
        metaMessage = formatNumber(progress, {
            locale,
            options: {
                style: 'unit',
                unit: 'percent',
                maximumFractionDigits: 0
            }
        });
    }
    else if (error) {
        metaMessage = error;
    }
    const definedActions = [
        previewFromActions ? { onClick: onPreview, text: t('preview'), icon: 'preview' } : undefined,
        { onClick: onEdit, text: t('edit'), icon: 'pencil' },
        { onClick: onDownload, text: t('download'), icon: 'download' },
        { onClick: onDelete, text: t('delete'), icon: 'trash' },
        { onClick: onOpen, text: t('link_open_in_tab_text'), icon: 'open' }
    ].flatMap(action => {
        if (!action || !action.onClick)
            return [];
        const { text, icon, onClick } = action;
        return [
            {
                id: text,
                text,
                icon,
                onClick: () => {
                    if (onClick)
                        onClick(id);
                }
            }
        ];
    });
    let visual;
    let contextualLabel;
    if (uploading) {
        visual = _jsx(Progress, { variant: 'ring', placement: 'inline', value: progress });
        contextualLabel = t('uploading_file', [name]);
    }
    else if (error) {
        visual = _jsx(StyledErrorIcon, { name: 'warn-solid' });
        contextualLabel = t('upload_failed', [name, error]);
    }
    else {
        visual = (_jsx(FileVisual, { type: format === 'url' ? 'link' : getKindFromMimeType(getMimeTypeFromFile(format ?? '') ?? ''), thumbnail: thumbnailError ? undefined : thumbnail, onThumbnailError: () => {
                setThumbnailError(true);
            } }));
        contextualLabel = name;
    }
    useEffect(() => {
        if (!activeElement?.isConnected && activeElementInItem && itemRef.current) {
            getFocusables(itemRef.current)[0]?.focus();
        }
    }, [progress, error, onCancel, onDelete, onPreview, onEdit, onDownload]);
    return (_jsxs(Flex, { as: StyledFileItem, container: {
            pad: [undefined, 0.5, undefined, undefined],
            alignItems: 'center',
            justify: 'start',
            gap: 1
        }, isDisabled: disabled, compactMode: compact, ref: itemRef, children: [visual, !previewFromActions && onPreview && !(error || uploading) ? (_jsxs(Button, { ...restProps, as: StyledPreviewTitle, variant: 'link', ref: setTextTarget, onClick: () => {
                    onPreview(id);
                }, "aria-label": t('preview_file', [name]), disabled: disabled, children: [name, format === 'url' && _jsx(Icon, { name: 'open' })] })) : (_jsx(Text, { ...restProps, as: StyledTextTitle, ref: setTextTarget, children: name })), metaMessage && (_jsxs(_Fragment, { children: [_jsx(Text, { as: StyledMeta, variant: 'secondary', error: error && !uploading, ref: setMetaTarget, children: metaMessage }), metaTarget && (_jsx(Tooltip, { target: metaTarget, describeTarget: false, smart: true, children: metaMessage }))] })), (error || uploading) && onCancel && (_jsx(StyledActionsWrapper, { meta: !!metaMessage, children: _jsx(Button, { label: t('cancel'), "aria-label": `${t('cancel')} - ${contextualLabel}`, variant: 'simple', compact: true, icon: true, onClick: () => onCancel(id), children: _jsx(Icon, { name: 'times' }) }) })), !(error || uploading) && !!definedActions.length && (_jsx(StyledActionsWrapper, { meta: !!metaMessage, children: _jsx(Actions, { items: definedActions, compact: true, iconOnly: true, contextualLabel: name, disabled: disabled }) })), textTarget && (_jsx(Tooltip, { target: textTarget, smart: true, describeTarget: false, children: name }))] }));
});
export default FileItem;
//# sourceMappingURL=FileItem.js.map