import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { TOGGLE } from '../../constants/schemaComponentTypes';
import { createNamespace } from '../../tools/namingTools';
import { generateUniqueID } from '../../tools/helpers';
import Avatar from '../../atoms/avatar/Avatar';
import Rating from '../../atoms/rating/Rating';
import Button from '../../atoms/button/Button';
import Icon from '../../atoms/icon/Icon';
import Tooltip from '../../atoms/tooltip/Tooltip';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/ProductReviewDetail.scss';

const n = createNamespace('ProductReviewDetail');

export const DEFAULT_AVATAR_SIZE = 82;
export const DEFAULT_AVATAR_SPACING = 28;
const DEFAULT_REVIEW_SECTIONS_SHOWN = 2;

const ProductReviewDetail = ({
    data: {
        reviewTags: tags,
        reviewAuthor: author,
        rating,
        title,
        sections,
        reviewLastModified
    },
    i18n,
    settings: {
        isAvatarVisible
    }
}) => {
    const i18nWithDefaults = { ...ProductReviewDetail.defaultProps.i18n, ...i18n };
    const [isReviewCollapsed, setReviewCollapsedState] = useState(true);
    const reviewList = sections && sections.length ? sections.filter(r => r.content) : [];
    const hasMoreSectionsThanDefault = reviewList.length > DEFAULT_REVIEW_SECTIONS_SHOWN;
    const hasHiddenReviewSections = isReviewCollapsed && hasMoreSectionsThanDefault;

    reviewList.length = hasHiddenReviewSections ? DEFAULT_REVIEW_SECTIONS_SHOWN : reviewList.length;

    const userJobDetails = author && [
        author.title,
        author.company && author.company.name,
        author.company && author.company.type
    ].filter(a => a);

    // Block Rendering
    const jobDetailBlock = userJobDetails && userJobDetails.length ? (
        <ul {...n('jobs').props}>
            {userJobDetails.map(detail => (
                <li key={detail}>{detail}</li>
            ))}
        </ul>
    ) : null;

    const tagsBlock = (
        <div {...n('tags').props}>
            {author && !!author.validatedReviewer && (
                <Tooltip
                    {...n('tagWrapper').props}
                    id={generateUniqueID([author.title, author.company.name])}
                    placeholder={i18nWithDefaults.validatedReviewer}
                >
                    <div {...n('tag').props}>{i18nWithDefaults.validatedReviewer}</div>
                </Tooltip>
            )}
            {tags && !!tags.length && tags.map((tag, index) => (
                <Tooltip
                    {...n('tagWrapper').props}
                    id={`tag-${generateUniqueID([tag.label, index, title, reviewLastModified])}`}
                    placeholder={tag.description}
                    key={`tag-${generateUniqueID([tag.label, index, title, reviewLastModified])}`}
                >
                    <div {...n('tag').props}>{tag.label}</div>
                </Tooltip>
            ))}
        </div>
    );

    const infoBlock = (
        <div {...n('info').props}>
            {rating && (
                <div {...n('rating').props}>
                    <Rating
                        rating={rating}
                        displayRatingNumber
                        i18nRating={{ label: i18nWithDefaults?.rating }}
                    />
                </div>
            )}
            {reviewLastModified && (
                <span {...n('date').props}>
                    {Intl.DateTimeFormat().format(new Date(reviewLastModified))}
                </span>
            )}
        </div>
    );

    const moreButton = (
        <div {...n('btnMoreReview').props}>
            <Button
                key={`more-review-${isReviewCollapsed}`}
                buttonType="link"
                type="primary"
                onClick={() => setReviewCollapsedState(!isReviewCollapsed)}
                data-testid="button:collaspable:moreButton"
            >
                {
                    isReviewCollapsed
                        ? i18nWithDefaults.showFullReview
                        : i18nWithDefaults.hideFullReview
                }
                <Icon
                    {...n('btnMoreReviewIcon').props}
                    type={isReviewCollapsed ? 'caretDown' : 'caretUp'}
                    width="12px"
                />
            </Button>
        </div>
    );

    const reviewBlock = (
        <div {...n('review').props}>
            <h5 {...n('reviewTitle').props}>{title}</h5>
            {reviewList && reviewList.length > 0 && (
                <div {...n('reviewContent').props}>
                    {reviewList.map(item => (
                        <div key={item.title || item.content} {...n('reviewItem').props}>
                            <span {...n('reviewTitle', 'small').props}>{item.title}</span>
                            {item.content && (
                                <p {...n('reviewDescription').props}>
                                    {item.content}
                                </p>
                            )}
                        </div>
                    ))}
                </div>
            )}
            {hasMoreSectionsThanDefault && moreButton}
        </div>
    );

    const componentVariables = {
        'avatar-spacing': Boolean(DEFAULT_AVATAR_SPACING) && `${DEFAULT_AVATAR_SPACING}px`
    };

    return (
        <div {...n('wrapper').withVariables(componentVariables).props}>
            {isAvatarVisible && author && (
                <div {...n('avatar').props}>
                    <Avatar name={author.name} picture={author.avatarUrl} />
                </div>
            )}
            <div {...n('comment').props}>
                {author && <h4 {...n('author').props}>{author.name}</h4>}
                {jobDetailBlock}
                {tagsBlock}
                {infoBlock}
                {reviewBlock}
            </div>
        </div>
    );
};

export const reviewDetailSchemaForm = {
    isAvatarVisible: {
        labelOn: 'uieditor.sfbComponent.productReviewDetail.isAvatarVisible.labelOn',
        labelOff: 'uieditor.sfbComponent.productReviewDetail.isAvatarVisible.labelOff',
        defaultValue: true,
        type: TOGGLE
    }
};

ProductReviewDetail.schema = () => ({
    name: 'ProductReviewDetail',
    id: 'uieditor.sfbComponent.productReviewDetail.title',
    form: reviewDetailSchemaForm
});

export const reviewItemShape = {
    id: PropTypes.string,
    tags: PropTypes.arrayOf(
        PropTypes.shape({
            type: PropTypes.string,
            lable: PropTypes.string,
            description: PropTypes.string
        })
    ),
    rating: PropTypes.number,
    title: PropTypes.string,
    author: PropTypes.shape({
        name: PropTypes.string,
        avatarUrl: PropTypes.string,
        company: PropTypes.shape({
            name: PropTypes.string,
            type: PropTypes.string
        }),
        validatedReviewer: PropTypes.bool
    }),
    lastModified: PropTypes.number,
    comments: PropTypes.arrayOf(
        PropTypes.shape({
            id: PropTypes.string,
            comment: PropTypes.string,
            author: PropTypes.shape({
                uuid: PropTypes.string,
                name: PropTypes.string,
                avatarUrl: PropTypes.string
            }),
            lastModified: PropTypes.number,
            official: PropTypes.bool,
            isCurrentUserComment: PropTypes.bool,
            actionEndpoint: PropTypes.string
        })
    ),
    sections: PropTypes.arrayOf(
        PropTypes.shape({
            title: PropTypes.string,
            content: PropTypes.string
        })
    ),
    actionEndpoints: PropTypes.shape({
        entry: PropTypes.string,
        comments: PropTypes.string
    }),
    reviewLastModified: PropTypes.string
};

ProductReviewDetail.propTypes = {
    data: PropTypes.shape(reviewItemShape),
    i18n: PropTypes.shape({
        showFullReview: PropTypes.string,
        hideFullReview: PropTypes.string,
        validatedReviewer: PropTypes.string,
        myRating: PropTypes.string,
        basedOnReviews: PropTypes.string,
        rating: PropTypes.string
    }),
    settings: PropTypes.shape({
        isAvatarVisible: PropTypes.bool
    })
};

ProductReviewDetail.defaultProps = {
    data: {},
    i18n: {
        showFullReview: 'Show full review',
        hideFullReview: 'Show less',
        validatedReviewer: 'Validated Reviewer',
        basedOnReviews: 'Based on {n} reviews',
        myRating: 'My rating:',
        rating: 'Rating {userRating} out of 5'
    },
    settings: {
        isAvatarVisible: reviewDetailSchemaForm.isAvatarVisible.defaultValue
    }
};

export default ProductReviewDetail;
