import type { FC } from 'react';
import React from 'react';
import { GlyphIcon } from '@theorchard/suite-icons';
import cx from 'classnames';
import { Tooltip } from '../tooltip';
import type { ComponentBaseProps } from '../../types';
import type { GlyphName24PX } from '@theorchard/suite-icons';

export const CLASS_NAME = 'GlyphToggle';

type allowedKeys = 'starred';

const toggleMap: Record<allowedKeys, GlyphName24PX> = {
    starred: 'notStarred',
};

export type GlyphToggleProps = ComponentBaseProps & {
    style?: React.CSSProperties;

    /**
     * Sets the initial toggle state
     */
    defaultValue?: boolean;

    /*
     * Disables the toggle functionality
     */
    disabled?: boolean;

    /*
     * The name of the glyph to show
     */
    name: keyof typeof toggleMap;

    /*
     * message to show on hover the glyph
     */
    tooltip?: string;

    /*
     * Size of the glyph
     */
    size: 24;

    /**
     * Defines a controlled state for the glyph
     */
    value?: boolean;

    /**
     * Callback with the new state of the glyph
     */
    onChange: (newState: boolean) => void;
};

/**
 * GlyphToggle is an actionable glyph that can be turned on and off and will change shape to indicate its state.
 *
 * @type atom
 * @status live
 * @tags buttons
 */
export const GlyphToggle: FC<GlyphToggleProps> = ({
    className,
    style,
    testId = CLASS_NAME,
    defaultValue = false,
    name,
    size,
    tooltip,
    value,
    disabled = false,
    onChange,
}) => {
    const [tgg, setToggled] = React.useState(value ?? defaultValue);
    const toggled = value ?? tgg;

    const glyphIconProps = {
        name: toggled ? name : toggleMap[name],
        size,
    };

    const onClick = () => {
        if (disabled) return;

        const newState = !toggled;
        setToggled(newState);
        onChange(newState);
    };

    const Component = (
        <div
            role="button"
            className={cx(CLASS_NAME, className, { toggled, disabled })}
            style={style}
            tabIndex={0}
            data-testid={testId}
            aria-disabled={disabled}
            aria-pressed={toggled}
            onClick={onClick}
            onKeyPress={onClick}
        >
            <GlyphIcon {...glyphIconProps} />
        </div>
    );

    if (tooltip)
        return (
            <Tooltip id={`${CLASS_NAME}-${name}-tooltip`} message={tooltip}>
                {Component}
            </Tooltip>
        );

    return Component;
};
