import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import withListener from '../withListener';
import { resourcesPropTypes } from '../../constants/prop-types/application/resources';
import { i18nPropTypes } from '../../constants/prop-types/application/resources/i18n';
import { DROPDOWN, SLIDER } from '../../constants/schemaComponentTypes';
import { NAMESPACES } from '../../constants/namespaces';
import { useItemsGrid } from '../../tools/widths/useItemsGrid';
import { useResponsive } from '../../tools/widths/useResponsive';
import ResourceCard from '../../atoms/resource-card/ResourceCard';
import Grid from '../../atoms/grid/Grid';
import './styles/Resources.scss';

const n = createNamespace('resources');
const getSizeClass = colNum => `size-${(colNum > 0 && colNum <= 5) ? colNum : 3}`;

const renderSection = (title, maxCol, renderItem, resourceItems) => (
    <>
        <h2 {...n('header', maxCol === 1 && 'center').withTestId().withE2EId().props}>
            {title}
        </h2>
        <Grid
            maxCol={maxCol}
            rowClass={n('gridRow').props.className}
            itemClass={n('gridItem').props.className}
        >
            {resourceItems.map(renderItem)}
        </Grid>
    </>
);

const Resources = ({
    data: {
        public: publicResources,
        reseller: resellerResources,
        i18n: i18nProp
    },
    settings
}) => {
    const i18n = { ...Resources.defaultProps.data.i18n, ...i18nProp };
    const settingsWithDefaults = { ...Resources.defaultProps.settings, ...settings };
    const { columns, spacing } = settingsWithDefaults;
    const [containerRef, gridColumns] = useItemsGrid();
    const { mediumUp, mediumDown } = useResponsive();

    const { documents: publicDocuments, videos: publicVideos } = publicResources;
    const { documents: resellerDocuments, videos: resellerVideos } = resellerResources;

    const publicResourceItems = publicDocuments.items.concat(publicVideos.items);
    const resellerResourceItems = resellerDocuments.items.concat(resellerVideos.items);

    const componentVariables = {};

    // Get the number of column for the Grid
    const maxCol = useMemo(() => {
        const columnSettings = columns ? Number(columns) : null;

        return mediumUp ? (columnSettings || gridColumns) : 1;
    }, [columns, gridColumns, mediumUp]);

    if (!publicResourceItems?.length && !resellerResourceItems?.length) {
        return null;
    }

    if (spacing || spacing === 0) {
        componentVariables['grid-gutter-width'] = `${spacing / 2}px`;
    }

    const renderItem = item => (
        <div {...n('itemContainer').withTestId().withE2EId().props} key={item.name}>
            <ResourceCard
                link={item.iFrameFriendlyURL}
                cardTitle={item.name}
                info={item.description}
                resourceType={item.resourceType}
                sizeClass={getSizeClass(maxCol)}
                hidePDFThumbnail={mediumDown}
                i18n={i18n}
            />
        </div>
    );

    return (
        <section {...n('container').withVariables(componentVariables).props} ref={containerRef}>
            {!!publicResourceItems?.length
                && renderSection(i18n.Resources, maxCol, renderItem, publicResourceItems)}
            {!!resellerResourceItems?.length
                && renderSection(i18n.ResellerResources, maxCol, renderItem, resellerResourceItems)}
        </section>
    );
};

const COLUMN_COUNT_OPTIONS = [
    { value: 1, label: '1' },
    { value: 2, label: '2' },
    { value: 3, label: '3' },
    { value: 4, label: '4' },
    { value: 5, label: '5' }
];

Resources.schema = () => ({
    name: 'ProductResources',
    title: 'uieditor.sfbComponent.resources.title',
    anchor: 'product-section-resources',
    iconName: 'file',
    orderableSection: [NAMESPACES.profile],
    form: {
        spacing: {
            title: 'uieditor.sfbComponent.resources.spacing.title',
            type: SLIDER,
            required: false,
            defaultValue: 28,
            options: {
                step: 1,
                min: 0,
                max: 30
            }
        },
        columns: {
            title: 'uieditor.sfbComponent.resources.column.title',
            type: DROPDOWN,
            defaultValue: 3,
            options: COLUMN_COUNT_OPTIONS
        }
    },
    marketplaceData: {
        public: 'application.resources.public',
        reseller: 'application.resources.reseller',
        i18n: 'application.resources.i18n'
    },
    requiredDataFunc: ({
        public: { documents: { items: publicDocumentsItems = [] }, videos: { items: publicVideosItems = [] } }
    }) => (
        publicDocumentsItems.concat(publicVideosItems).length
    )
});

Resources.propTypes = {
    data: PropTypes.shape({
        public: PropTypes.shape(resourcesPropTypes),
        reseller: PropTypes.shape(resourcesPropTypes),
        i18n: PropTypes.shape(i18nPropTypes)
    }),
    settings: PropTypes.shape({
        spacing: PropTypes.number,
        columns: PropTypes.string
    })
};

const resourcesDefaultProps = {
    documents: {
        items: []
    },
    videos: {
        items: []
    }
};

Resources.defaultProps = {
    data: {
        public: resourcesDefaultProps,
        reseller: resourcesDefaultProps,
        i18n: {
            Resources: 'Resources',
            Videos: 'Videos',
            Documents: 'Documents',
            ResellerResources: 'Reseller Resources',
            Download: 'Download',
            fileFormat: {
                pdf: {
                    label: 'PDF',
                    fullName: 'Portable Document Format'
                }
            }
        }
    },
    settings: {}
};

export default withListener(Resources);
