import React, { useMemo, useState } from 'react';
import PropTypes from 'prop-types';
import merge from 'deepmerge';
import { createNamespace } from '../../tools/namingTools';
import Button from '../../atoms/button/Button';
import Icon from '../../atoms/icon/Icon';
import GridContainer from '../../atoms/grid-container/GridContainer';
import Question, { questionShape } from './atoms/product-question-item/ProductQuestionItem';
import withListener from '../withListener';
import { NAMESPACES } from '../../constants/namespaces';
import './styles/ProductQuestions.scss';

const n = createNamespace('ProductQuestions');

const DEFAULT_N_QUESTIONS_SHOWN = 4;
const QUESTIONS_LIST_ID = 'questionsList';

export const ProductQuestionsComponent = ({
    data: {
        isLoggedIn,
        questions = {}
    }
}) => {
    const { items, addQuestionURL, i18n: i18nProp } = questions;

    // memoize i18n defaults merge, as it does not change from state to state
    const i18nWithDefaults = useMemo(
        () => (
            merge(ProductQuestionsComponent.defaultProps.data.questions.i18n, i18nProp)
        ),
        [i18nProp]
    );

    const [isCollapsed, setCollapsed] = useState(true);

    const itemsToShow = items && (isCollapsed ? items.slice(0, DEFAULT_N_QUESTIONS_SHOWN) : items);

    let showMoreBlock = null;

    if (items && items.length > DEFAULT_N_QUESTIONS_SHOWN) {
        const buttonLabel = isCollapsed
            ? `${i18nWithDefaults.labels.displayQuestions} (${items.length})`
            : i18nWithDefaults.labels.hideQuestions;
        const iconType = isCollapsed ? 'caretDown' : 'caretUp';
        showMoreBlock = (
            <div {...n('seeAll').props}>
                <Button
                    aria-expanded={!isCollapsed ? 'true' : 'false'}
                    aria-controls={QUESTIONS_LIST_ID}
                    buttonType="link"
                    type="primary"
                    onClick={() => setCollapsed(!isCollapsed)}
                >
                    {buttonLabel}
                    <Icon type={iconType} width="12px" {...n('seeAllIcon').props} />
                </Button>
            </div>
        );
    }

    const redirectToQuestionForm = () => {
        const loginUrl = `/login?stateToken=${addQuestionURL}`;
        // Check if user is logged in
        if (isLoggedIn) {
            // Redirect to Questions Form Page
            window.location.assign(addQuestionURL);
        } else {
            window.location.assign(loginUrl);
        }
    };

    return (
        <GridContainer>
            <section {...n('container').props}>
                <div {...n('hgroup').withE2EId().props}>
                    <h2 {...n('title').withE2EId().props}>{i18nWithDefaults.headers.questionTitle}</h2>
                    <div {...n('askQuestion').withTestId().props}>
                        <Button
                            type="primary"
                            onClick={redirectToQuestionForm}
                            aria-label={i18nWithDefaults.labels.goToAskAQuestion}
                        >
                            {i18nWithDefaults.labels.askQuestion}
                        </Button>
                    </div>
                </div>
                <div {...n('listWrapper').withE2EId().props}>
                    {(items && !items.length) && <p {...n('description').props}>{i18nWithDefaults.headers.noQuestion}</p>}
                    {itemsToShow && (
                        <ul id={QUESTIONS_LIST_ID} {...n('list').props} aria-label={i18nWithDefaults.labels.questions}>
                            {itemsToShow.map(item => (
                                <li {...n('questionWrapper').props} key={item.id}>
                                    <Question data={item} i18n={i18nWithDefaults.labels} />
                                </li>
                            ))}
                        </ul>
                    )}
                </div>
                {showMoreBlock}
            </section>
        </GridContainer>
    );
};

ProductQuestionsComponent.schema = () => ({
    name: 'ProductQuestions',
    title: 'uieditor.sfbComponent.productQuestion.title',
    anchor: 'product-section-questions',
    iconName: 'tip',
    form: {},
    orderableSection: [NAMESPACES.profile],
    marketplaceData: {
        isLoggedIn: 'config.user.isLoggedIn',
        questions: 'application.questions'
    }
});

ProductQuestionsComponent.propTypes = {
    data: PropTypes.shape({
        questions: PropTypes.shape({
            items: PropTypes.arrayOf(
                PropTypes.shape(questionShape)
            ),
            addQuestionURL: PropTypes.string,
            i18n: PropTypes.object
        }),
        isLoggedIn: PropTypes.bool.isRequired
    })
};

ProductQuestionsComponent.defaultProps = {
    data: {
        isLoggedIn: false,
        questions: {
            items: [],
            addQuestionURL: '',
            i18n: {
                headers: {
                    noQuestion: 'No questions have been asked.',
                    whatWouldYou: 'What would you like to know about this product?',
                    nbQuestions: 'Questions',
                    questionTitle: 'Questions And Answers',
                    questions: 'Questions'
                },
                labels: {
                    search: 'Search',
                    askQuestion: 'Ask a Question',
                    developerAnswer: 'Developer Answer',
                    answer: 'Answer',
                    edit: 'Edit',
                    delete: 'Delete',
                    cancel: 'Cancel',
                    confirm: 'Confirm',
                    resultsStr: '4 Results',
                    question: 'Question',
                    questions: 'Questions',
                    description: 'Description',
                    submit: 'Submit',
                    signUp: 'Sign Up to Ask a Question',
                    submitComment: 'Submit Answer',
                    writeYourAnswerHere: 'Write your answer here',
                    answerQuestion: 'Answer Question',
                    displayQuestions: 'Display all questions',
                    hideQuestions: 'Hide all questions',
                    successAlert: 'Thank you for your question! We will post it shortly.',
                    errorAlert: 'Error has occurred.',
                    goToAskAQuestion: 'Go to "ask a question" form',
                    answersTo: 'Answers to'
                },
                messages: {
                    confirm: {
                        deleteEntry: 'Please confirm deleting this question.',
                        deleteComment: 'Please confirm deleting this answer.'
                    },
                    success: {
                        deleteEntry: 'Question successfully deleted',
                        deleteComment: 'Answer successfully deleted',
                        postEntry: 'Thank you for asking a question!  It will be posted shortly.',
                        postComment: 'Thank you for your answer!  It will be posted shortly.'
                    },
                    error: {
                        deleteEntry: 'Unable to delete question.',
                        deleteComment: 'Unable to delete answer.',
                        postEntry: 'You must log in to ask a question.',
                        postComment: 'You must log in to ask a question.',
                        textareaMaxLength: 'Must be at most 2048 characters',
                        fieldRequired: 'Required'
                    }
                }
            }
        }
    }
};

export default withListener(ProductQuestionsComponent);
