import React, { useState } from 'react';
import PropTypes from 'prop-types';
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;

export const ProductQuestionsComponent = ({
    data: {
        questions = {}
    }
}) => {
    const { items, isLoggedIn, addQuestionURL, i18n: i18nProp } = questions;
    // make sure that all i18n are filled with defaults, as React's default props are shallow merged
    const i18n = i18nProp ? {
        ...i18nProp,
        ...ProductQuestionsComponent.defaultProps.data.questions.i18n
    } : {
        ...ProductQuestionsComponent.defaultProps.data.questions.i18n
    };
    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 ? i18n.labels.showQuestions : i18n.labels.hideQuestions;
        const iconType = isCollapsed ? 'caretDown' : 'caretUp';
        showMoreBlock = (
            <div {...n('seeAll').props}>
                <Button 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);
        }
    };

    // make Q / A labels for each question
    const questionLabels = {
        question: i18n.labels.question.trim()[0].toUpperCase(),
        answer: i18n.labels.answer.trim()[0].toUpperCase()
    };

    return (
        <GridContainer>
            <section {...n('container').props}>

                <div {...n('hgroup').withE2EId().props}>
                    <h1 {...n('title').withE2EId().props}>{i18n.headers.questionTitle}</h1>
                    <div {...n('askQuestion').props}>
                        <Button type="primary" onClick={redirectToQuestionForm}>{i18n.labels.askQuestion}</Button>
                    </div>
                </div>
                <div {...n('list').withE2EId().props}>
                    {(items && !items.length) && <p {...n('description').props}>{i18n.headers.noQuestion}</p>}
                    {itemsToShow && itemsToShow.map(item => (
                        <Question key={item.id} data={item} i18n={questionLabels} />
                    ))}
                </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)
            ),
            isLoggedIn: PropTypes.bool.isRequired,
            addQuestionURL: PropTypes.string,
            i18n: PropTypes.object
        })
    })
};

ProductQuestionsComponent.defaultProps = {
    data: {
        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',
                    description: 'Description',
                    submit: 'Submit',
                    signUp: 'Sign Up to Ask a Question',
                    submitComment: 'Submit Answer',
                    writeYourAnswerHere: 'Write your answer here',
                    answerQuestion: 'Answer Question',
                    showQuestions: 'See all questions',
                    hideQuestions: 'Hide all questions',
                    successAlert: 'Thank you for your question! We will post it shortly.',
                    errorAlert: 'Error has occurred.'
                },
                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);
