import React, { useState, useEffect } from 'react';
import { injectIntl, FormattedMessage } from 'react-intl';
import get from 'lodash/get';
import CapInput from '@capillarytech/cap-ui-library/CapInput';
import CapLabel from '@capillarytech/cap-ui-library/CapLabel';
import CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapHeading from '@capillarytech/cap-ui-library/CapHeading';
import CapDrawer from '@capillarytech/cap-ui-library/CapDrawer';
import CapCustomCard from '@capillarytech/cap-ui-library/CapCustomCard';
import CapHeader from '@capillarytech/cap-ui-library/CapHeader';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import { CAP_SPACE_12, CAP_SPACE_08, FONT_COLOR_05, FONT_COLOR_04 } from '@capillarytech/cap-ui-library/styled/variables';
import TagList from '../../../TagList';
import LineDrawer from '../Drawer';
import messages from './messages';
import style from './style';
import withStyles from '../../../../hoc/withStyles';
import globalMessages from '../../../Cap/messages';
import { validateTags } from '../../../../utils/tagValidations';
import moment from 'moment';
import { GET_TRANSLATION_MAPPED } from '../../../../constants/unified';

const { TextArea } = CapInput;
const {CapCustomCardList} = CapCustomCard;


const charLimit = 1600;

export const LineText = ({
    className,
    id,
    intl: { formatMessage },
    isFullMode,
    tags,
    injectedTags,
    inheritedTitleStyle,
    inheritedContentStyle,
    getDefaultTags,
    globalActions,
    location,
    index,
    updateMessageState,
    content,
    activeKey,
    Templates,
    getAllTemplates,
    selectedOfferDetails,
}) => {
    if (activeKey !== 'text') {
        return null;
    }

    const [errorMessageTextarea, updateErrorMessageTextArea] = useState(false);
    const [isCreateNew, updateCreateNew] = useState(isFullMode);
    const [errorMessageTitle, updateErrorMessageTitle] = useState(false);
    const [messageContent, updateTextMessageContent] = useState('');
    const [messageTitle, updateTextMessageTitle] = useState('');
    const [isDrawerRequired, updateDrawerRequirement] = useState(false);
    const [selectedTemplate, updateSelectedTemplate] = useState();
    const [translationLang, updateTranslationLang] = useState('en');

    useEffect(() => {
        const { messageTitle = '', messageContent = '', type, isInit } = content;
        if (type === 'text') {
            if (messageContent) {
                updateCreateNew(true);
                updateTextMessageContent(messageContent);
                updateTextMessageTitle(messageTitle);
            }
            if (isInit) {
                updateCreateNew(isFullMode);
                updateTextMessageContent('');
                updateTextMessageTitle('');
            }
        }
    }, [content]);

    //To Find from which locale user is loggedin
    useEffect(() => {
      const user = localStorage.getItem("user");
      let locale = "en";
      if (user) {
        locale = JSON.parse(user)?.lang || locale;
      }
      locale = GET_TRANSLATION_MAPPED?.[locale];
      moment.locale(locale);
      updateTranslationLang(locale);
    }, []);
     
    useEffect(() => {
        if (messageContent && (isFullMode ? messageTitle : true)) {
            updateMessageState({
                isError: (messageContent.length > charLimit) || (!messageContent || !(isFullMode ? messageTitle : true) || (errorMessageTextarea || errorMessageTitle)),
                messageContent,
                messageTitle,
                index,
                type: 'text',
                messageType: 'text',
            });
        }
    }, [errorMessageTitle, messageContent, messageTitle, errorMessageTextarea]);

    useEffect(() => {
        const getTagsQuery = {
          layout: 'LINE',
          type: 'TAG',
          context:
            location?.query?.type === 'embedded'
              ? 'outbound'
              : 'default',
          embedded:
            location?.query?.type === 'embedded'
              ? location?.query?.type
              : 'full',
        };
        if (getDefaultTags) {
          getTagsQuery.context = getDefaultTags;
        }
        globalActions.fetchSchemaForEntity(getTagsQuery);
    }, []);

    const handleOnTagsContextChange = (data) => {
        const query = {
        layout: 'LINE',
        type: 'TAG',
        context:
            (data || '').toLowerCase() === 'all' ? 'default' : (data || '').toLowerCase(),
        embedded:
            location?.query?.type === 'embedded'
            ? location?.query?.type
            : 'full',
        };
        globalActions.fetchSchemaForEntity(query);
    };

    const updateTextContentError = (value) => {
        let errorMessage = false;
        const { valid, isBraceError } = validateTags({
            content: value,
            tagsParam: tags,
            location,
            tagModule: 'outbound',
            isFullMode,
        }) || {};
        if (value.trim() === '') {
            errorMessage = formatMessage(messages.emptyContentErrorMessage);
        } else if (value.length > charLimit) {
            errorMessage = formatMessage(messages.limitExceededContentErrorMessage);
        } else if (isBraceError) {
            errorMessage = formatMessage(globalMessages.unbalanacedCurlyBraces);
        } else if (!valid && !isFullMode) {
            errorMessage = formatMessage(messages.invalidTagError);
        }
        updateErrorMessageTextArea(errorMessage);
    }

    const onTextContentChange = ({ target: { value } }) => {
        updateTextMessageContent(value);
        updateTextContentError(value);
        updateMessageState({
            isError: (value.length > charLimit) || (!value || !(isFullMode ? messageTitle : true) || (!value || errorMessageTitle)),
            messageContent: value,
            messageTitle,
            index,
            type: 'text',
            messageType: 'text',
        });
    }

    const updateTextTitleError = (value) => {
        let errorMessage = false;
        if (value === '') {
            errorMessage = formatMessage(messages.emptyTitleErrorMessage);
        }
        updateErrorMessageTitle(errorMessage);
    }

    const onTextTitleChange = ({ target: { value } }) => {
        updateTextMessageTitle(value);
        updateTextTitleError(value);
        updateMessageState({
            isError: (messageContent.length > charLimit) || (!messageContent || !(isFullMode ? value : true) || (!value || errorMessageTextarea)),
            messageContent,
            messageTitle: value,
            index,
            type: 'text',
            messageType: 'text',
        });
    }

    const onTagSelect = (data) => {
        const messageData = `${messageContent}{{${data}}}`;
        updateTextMessageContent(messageData);
        updateTextContentError(messageData);
    }

    const setNewContent = () => updateCreateNew(true);

    const onSelectTemplate = (event) => {
        event.stopPropagation();
        updateDrawerRequirement(true);
    }

    const getLineTextSection = () => {
        if (!isCreateNew) {
            return (
                <div className="form-builder-dragger" style={{
                    textAlign: 'center',
                    border: '2px dashed lightgrey',
                    minHeight: 120,
                    padding: 60
                }}>
                <CapHeader
                    className="choice-title"
                    size="regular"
                    title={formatMessage(messages.textMessageAddLabel)}
                    style={{ marginBottom: 12 }}
                />
                
                <CapButton
                    className="create-button"
                    type="secondary"
                    style={{marginRight: CAP_SPACE_08}}
                    onClick={setNewContent}
                >
                    <FormattedMessage {...messages.textMessageCreateNew} />
                </CapButton>

                <CapHeading className="" type="label6" style={{ display: 'inline-block' }}>
                    <FormattedMessage {...messages.textMessageORLabel} />
                </CapHeading>

                <CapButton
                    className="dragger-button"
                    type="secondary"
                    style={{marginLeft: CAP_SPACE_08}}
                    onClick={onSelectTemplate}
                >
                    <FormattedMessage {...messages.textMessageSelectTemplate} />
                </CapButton>
            </div>);
        }
        return (
            <>
                <TextArea
                    id={`${id}_textarea`}
                    placeholder={formatMessage(messages.textMessagePlaceholder)}
                    className={`${errorMessageTextarea ? 'error' : ''}`}
                    errorMessage={errorMessageTextarea}
                    label={(
                        <>
                            <FormattedMessage {...messages.textMessage} />
                            <CapLabel type="label2" className="word-count">
                                <FormattedMessage {...messages.charCount} />
                                {(messageContent || '').length}/{charLimit}
                            </CapLabel>
                        </>
                    )}
                    autosize={false}
                    onChange={onTextContentChange}
                    style={inheritedContentStyle || {}}
                    className="text-template-content"
                    defaultValue={messageContent || ''}
                    value={messageContent || ''}
                    rows={5}
                    cols={2}
                />
                <CapRow type='flex' align='middle' justify='end' fullWidth>
                    <TagList
                        key={`${id}_tags`}
                        moduleFilterEnabled={location && location?.query && location?.query?.type !== 'embedded'}
                        label={formatMessage(messages.addLabels)}
                        onTagSelect={onTagSelect}
                        onContextChange={handleOnTagsContextChange}
                        location={location}
                        tags={tags || []}
                        injectedTags={injectedTags || {}}
                        // className={val.className ? val.className : ''}
                        id={`${id}_tags`}
                        userLocale={translationLang}
                        selectedOfferDetails={selectedOfferDetails}
                />
                </CapRow>
            </>
        );
    }

    const onTemplateSelection = (template) => {
        const content = get(template, 'versions.base.content.messages[0].text', '');
        updateSelectedTemplate(template);
        updateTextMessageContent(content);
        updateErrorMessageTextArea(!content);
        updateDrawerRequirement(false);
        updateCreateNew(true);
    }

    const getLineTextDrawerContent = () => {
        const lineTextTemplates = Templates.templates;
        if (!lineTextTemplates) {
            return null;
        }

        const cardDataList = [];
        lineTextTemplates.forEach(template => {
            let templateData = {};
            const {
                content: {
                messages: [{
                    text = '',
                }] = [{}],
                } = {},
            } = template.versions.base;
            templateData.content = text;
            templateData.title = template.name;
            templateData.key = template.name;
            templateData.hoverOption = (
                <CapButton onClick={() => onTemplateSelection(template)}>
                    <FormattedMessage {...messages.select} />
                </CapButton>
            );
            if (text) {
                cardDataList.push(templateData);
            }
        });
        return (
        <>
            <CapHeading type="h3" className="drawer-head">
                {formatMessage(messages.lineTemplateText)}
            </CapHeading>
            <LineDrawer
                getAllTemplates={getAllTemplates}
                cardDataList={cardDataList}
                isDrawer={isDrawerRequired}
                className="drawer-head"
                searchPlaceholder={formatMessage(messages.searchText)}
                Templates={Templates}
            />
        </>
        );
    };

    return (
        <div className={className}>
            {
                isFullMode
                ? (
                    <CapInput
                        id={`${id}_input`}
                        onChange={onTextTitleChange}
                        errorMessage={errorMessageTitle}
                        className="text-template-title"
                        style={inheritedTitleStyle || {}}
                        placeholder={formatMessage(messages.textMessageTitlePlaceholder)}
                        defaultValue={messageTitle || ''}
                        value={messageTitle || ''}
                        size="default"
                        label={formatMessage(messages.textMessageTitleLabel)}
                        data-testid="template_name"
                    />
                )
                : null
            }
            {
                getLineTextSection()
            }
            <CapDrawer
                content={getLineTextDrawerContent()}
                visible={isDrawerRequired}
                width={624}
                onClose={() => updateDrawerRequirement(false)}
            />
        </div>
    )
}


export default injectIntl(withStyles(LineText, style));
