import React, { useState } from 'react';
import { ListBox, Sidecar, Tooltip } from '@theorchard/suite-components';
import { GlyphIcon } from '@theorchard/suite-icons';
import './styles.scss';
import type { ListViewItem } from '@theorchard/suite-components';

export interface SidecarTriggerItem {
    /** Primary text shown in the list row. */
    label: string;
    /** Secondary text shown below the label. */
    subtitle?: string;
}

export interface SidecarTriggerProps {
    /** Unique id used for tooltip/test ids. */
    id: string;
    /** Sidecar drawer title. */
    title: string;
    /** Heading inside the sidecar body, e.g. "Tracks (5)". */
    heading: string;
    items: SidecarTriggerItem[];
    /** Tooltip text when there are no items (button is disabled). */
    emptyTooltip?: string;
    /** Empty-search message inside the ListBox. */
    noMatchText?: string;
    /** Hide the search input (e.g. for short lists that don't need filtering). */
    hideFilter?: boolean;
}

export const SidecarTrigger: React.FC<SidecarTriggerProps> = ({
    id,
    title,
    heading,
    items,
    emptyTooltip = 'No details to show.',
    noMatchText = 'No matches for that search.',
    hideFilter = false,
}) => {
    const [isOpen, setIsOpen] = useState(false);
    const hasOptions = items.length > 0;
    const options: ListViewItem[] = items.map((item, idx) => ({
        label: item.label,
        subtitle: item.subtitle ?? '',
        value: idx.toString(),
    }));

    const button = (
        <button
            type="button"
            className="TermsDetail-sidecarButton"
            onClick={() => setIsOpen(true)}
            disabled={!hasOptions}
            data-testid={`sidecarTrigger-${id}`}
        >
            <GlyphIcon name="moreDetails" size={16} />
        </button>
    );

    return (
        <>
            {hasOptions ? (
                button
            ) : (
                <Tooltip
                    id={`sidecarTrigger-${id}-tooltip`}
                    message={emptyTooltip}
                    placement="left"
                >
                    {button}
                </Tooltip>
            )}
            <Sidecar
                isOpen={isOpen}
                onRequestClose={() => setIsOpen(false)}
                title={title}
            >
                <div className="TermsDetail-sidecarBody">
                    <h5 className="TermsDetail-sidecarHeading">{heading}</h5>
                    <ListBox
                        bordered
                        variant="static"
                        className="TermsDetail-sidecarListBox"
                        options={options}
                        optionsMatchBy="all"
                        noMatchText={noMatchText}
                        hideFilter={hideFilter}
                    />
                </div>
            </Sidecar>
        </>
    );
};
