import type { FC } from 'react';
import React from 'react';
import { Icon } from '@theorchard/suite-icons';
import cx from 'classnames';
import { Form } from 'react-bootstrap';
import { HelpTooltip } from '../helpTooltip';
import { t } from './i18n';
import type { IconName16px } from '@theorchard/suite-icons';

export const CLASS_NAME = 'FormLabel';

export interface LabelProps {
    className?: string;

    testId?: string;

    /**
     * If true will make the label red
     */
    hasError?: boolean;

    /**
     * If the label should have a help icon, pass the id and message with this prop
     */
    help?: {
        message: JSX.Element | string;
        id: string;
    };

    /**
     * Do not hide tooltip when hovering over it.
     */
    helpHideOnHover?: boolean;

    /**
     * @deprecated No longer in use. Use `isOptional` to indicate optional fields.
     */
    isRequired?: boolean;

    /**
     * Class name applied to the <label> element.
     */
    labelClassName?: string;

    /**
     * The label text
     */
    text: string;

    /**
     * Icons, placed before label text
     */
    icons?: IconName16px[];

    /**
     * Appends text indicating the field is optional
     */
    isOptional?: boolean;
}

/**
 * Label is used to create a caption for a form control. It has optional properties to indicate whether the form field is optional or not, or to provides a HelpTooltip with more information.
 *
 * @type molecule
 * @status revised
 * @tags form-elements
 */
export const Label: FC<LabelProps> = ({
    className,
    labelClassName,
    testId = CLASS_NAME,
    help,
    isOptional,
    isRequired,
    text,
    hasError,
    helpHideOnHover,
    icons = [],
}) => {
    const withOptional = isOptional || (isRequired !== undefined && isRequired === false);

    const iconsArray = icons.length > 0 && (
        <span className={`${CLASS_NAME}-icons`}>
            {icons.map((name, i) => (
                <Icon name={name} size={16} key={`${name}${i}`} />
            ))}
        </span>
    );

    const optionalText = <span className={`${CLASS_NAME}-optional`}> ({t('optional')})</span>;

    return (
        <div
            className={cx(CLASS_NAME, className, {
                [`${CLASS_NAME}-error`]: hasError,
            })}
            data-testid={testId}
        >
            <Form.Label className={labelClassName}>
                {iconsArray}

                {text}

                {withOptional && optionalText}

                {help && (
                    <HelpTooltip
                        message={help.message}
                        id={help.id}
                        hideOnHover={helpHideOnHover}
                    />
                )}
            </Form.Label>
        </div>
    );
};
