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

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

const Resources = ({
    data: { header, documents, videos },
    settings
}) => {
    const settingsWithDefaults = { ...Resources.defaultProps.settings, ...settings };
    const { columns, spacing } = settingsWithDefaults;
    const [containerRef, gridColumns] = useItemsGrid();
    const { mediumUp } = useResponsive();
    const resourceItems = documents.items.concat(videos.items);
    const componentVariables = {};

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

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

    if (!resourceItems || !resourceItems.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)}
            />
        </div>
    );

    return (
        <div {...n('container').withVariables(componentVariables).props} ref={containerRef}>
            <div {...n('header', maxCol === 1 && 'center').withTestId().withE2EId().props}>
                {resourceItems.length ? header : null}
            </div>
            <Grid
                maxCol={maxCol}
                rowClass={n('gridRow').props.className}
                itemClass={n('gridItem').props.className}
            >
                {resourceItems.map(renderItem)}
            </Grid>
        </div>
    );
};

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,
            validation: {
                availableOptions: COLUMN_COUNT_OPTIONS.map(({ value }) => value),
                message: 'uieditor.sfbComponent.dropdown.validation.message',
                default: 'uieditor.sfbComponent.dropdown.defaultValue'
            }
        }
    },
    marketplaceData: {
        header: 'application.resources.i18n.Resources',
        documents: 'application.resources.public.documents',
        videos: 'application.resources.public.videos'
    },
    requiredDataFunc: ({
        documents: { items: documentsItems = [] },
        videos: { items: videosItems = [] }
    }) => (
        documentsItems.concat(videosItems).length
    )
});

Resources.propTypes = {
    settings: PropTypes.shape({
        spacing: PropTypes.number,
        columns: PropTypes.number
    }),
    data: PropTypes.shape({
        header: PropTypes.string,
        documents: PropTypes.shape({
            items: PropTypes.arrayOf(
                PropTypes.shape({
                    id: PropTypes.number,
                    resourceType: PropTypes.string,
                    name: PropTypes.string,
                    link: PropTypes.string,
                    scribdKey: PropTypes.string,
                    description: PropTypes.string,
                    iFrameFriendlyURL: PropTypes.string,
                    resellerAccess: PropTypes.bool
                })
            )
        }),
        videos: PropTypes.shape({
            items: PropTypes.arrayOf(
                PropTypes.shape({
                    id: PropTypes.number,
                    resourceType: PropTypes.string,
                    name: PropTypes.string,
                    link: PropTypes.string,
                    scribdKey: PropTypes.string,
                    description: PropTypes.string,
                    iFrameFriendlyURL: PropTypes.string,
                    resellerAccess: PropTypes.bool
                })
            )
        })
    })
};

Resources.defaultProps = {
    data: {
        header: null,
        documents: {
            items: []
        },
        videos: {
            items: []
        }
    },
    settings: {}
};

export default withListener(Resources);
