import React, { FC, useState, useMemo } from 'react';
import { Card } from '@orchard/frontend-react-components';
import cx from 'classnames';
import { formatMessage } from '@orchard/frontend-localization';
import { ComparisonSongs, SectionDataComponentProps, SectionDataProps } from 'src/definitions';
import { useComparisonData } from 'src/queries';
import { DEFAULT_SECTION_DATA } from 'src/constants';
import { TERM_HEADER } from 'src/components/performanceOverTime/PerformanceOverTime';

export const CLASSNAME = 'CompareSection';
export const CLASSNAME_HEADER = `${CLASSNAME}-header`;
export const CLASSNAME_HEADER_TITLE = `${CLASSNAME}-header-title`;
export const CLASSNAME_CONTENT = `${CLASSNAME}-content`;
export const CLASSNAME_EMPTY = `${CLASSNAME}-empty`;
export const CLASSNAME_FOOTER = `${CLASSNAME}-footer`;

export interface Props {
    headerText: string;
    Content: FC<ComparisonSongs & SectionDataComponentProps>;
    EmptyState?: FC;
    HeaderMenu?: FC<SectionDataComponentProps>;
    className?: string;
}

const CompareSection: FC<Props> = ({
    headerText, Content, EmptyState, HeaderMenu, className
}) => {
    const [sectionData, setSectionData] = useState<SectionDataProps>(DEFAULT_SECTION_DATA);
    const sectionDataProps = useMemo<SectionDataComponentProps>(() => ({
        sectionData,
        setSectionData: newValue => setSectionData({ ...sectionData, ...newValue }),
    }), [sectionData]);
    const data = useComparisonData();
    const { selectedSongIds } = data;


    function hasDataOrShouldBeDisplayedEmpty() {
        return selectedSongIds.length || headerText === formatMessage(TERM_HEADER);
    }

    return (
        hasDataOrShouldBeDisplayedEmpty()
            ? (
                <Card className={cx(CLASSNAME, className)}>
                    <div className={CLASSNAME_HEADER}>
                        <h4 className={cx(CLASSNAME_HEADER_TITLE, 'mr-auto')}>
                            {headerText}
                        </h4>

                        {HeaderMenu && <HeaderMenu {...sectionDataProps} />}
                    </div>
                    {
                        selectedSongIds.length
                            ? <Content {...data} {...sectionDataProps} />
                            : (
                                <div className={CLASSNAME_EMPTY}>
                                    {EmptyState && <EmptyState />}
                                </div>
                            )
                    }
                </Card>
            )
            : <div />
    );
};

export default CompareSection;
