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 CapTab from '@capillarytech/cap-ui-library/CapTab';
import CapHeading from '@capillarytech/cap-ui-library/CapHeading';
import CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
import CapDrawer from '@capillarytech/cap-ui-library/CapDrawer';
import CapHeader from '@capillarytech/cap-ui-library/CapHeader';
import CapTooltip from '@capillarytech/cap-ui-library/CapTooltip';
import CapTooltipWithInfo from '@capillarytech/cap-ui-library/CapTooltipWithInfo';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import isEmpty from 'lodash/isEmpty';
import LineDrawer from '../Drawer';
import style from './style';
import { CAP_G06, FONT_COLOR_01, FONT_COLOR_02, CAP_SPACE_08, CAP_WHITE, CAP_SPACE_24, CAP_SPACE_04 } from '@capillarytech/cap-ui-library/styled/variables';
import withStyles from '../../../../hoc/withStyles';
import { getCdnUrl } from '../../../../utils/cdnTransformation';

import LineImageCarouselContent from './Content';

import messages from './messages';
import {
	MAX_CAROUSEL_ALLOWED,
	TEXT_ACTION_TYPE,
	MESSAGE_ACTION_TYPE,
	URL_ACTION_TYPE,
	MAX_ALLOWED_TITLE_LENGTH,
	FLEX,
	CAROUSEL,
	TEMPLATE,
} from './constants';

export const LineImageCarousel = (props) => {

	const {
		className,
		id,
		intl: { formatMessage },
		isFullMode,
		inheritedTitleStyle,
		Line,
		index,
		updateMessageState,
		content,
		activeKey,
		Templates,
		getAllTemplates,
	} = props;

	if (activeKey !== FLEX) {
		return null;
	}

	const defaultActiveIndex = 0;

	const defaultCarouselContent = {
		messageTitle: '',
		originalContentUrl: '',
		aspectRatio: '',
		previewImageUrl: '',
		type: CAROUSEL,
	};

	const [carouselImages, updateCarouselImage] = useState([defaultCarouselContent]);
	const [activeIndex, updateActiveIndex] = useState(`${defaultActiveIndex}`);
	const [errorMessageTitle, updateErrorMessageTitle] = useState(false);
	const [messageTitle, updateTextMessageTitle] = useState('');
	const [isTemplateDrawerRequired, updateTemplateDrawerRequirement] = useState(false);
	const [isCreateNew, updateCreateNew] = useState(isFullMode);
	const [selectedTemplate, updateSelectedTemplate] = useState();
  const [altText, updateTitle] = useState('');
	const [errorTitle, updateErrorTitle] = useState(false);

	useEffect(() => {
		const { messageTitle = '', type, template, altText, contents } = content;
		if ([TEMPLATE, FLEX].includes(type)) {
			updateCreateNew(!isFullMode ? !!(template || contents) : true);
			if (messageTitle) {
				updateTextMessageTitle(messageTitle);
			}
			if (altText) {
				updateTitle(altText);
			}
			if (template || contents) {
			  	const validCarouselImages = [];
				if (template?.type === CAROUSEL || contents?.type === CAROUSEL ) {
                    const { contents: innerContents = [] } = contents || template || [];
                    	    innerContents.forEach((content = {}, index) => {							const {
								footer: {
									contents: [{
										action: {
											text = '',
											label = '',
											type: buttonType = '',
											uri,
										} = {},
									}] = [],
								} = {},
								hero: {
									url = '',
									aspectRatio = '',
								} = {},
							} = content || {};
							validCarouselImages.push({
								activeIndex: index,
								originalContentUrl: getCdnUrl({url: url, channelName: 'LINE', channelSubType: 'CARD'}),
								aspectRatio,
								selectedActionType: buttonType ? (buttonType === MESSAGE_ACTION_TYPE ? TEXT_ACTION_TYPE : URL_ACTION_TYPE) : '',
								actionContent: text || uri,
								actionLabel: label,
								type: CAROUSEL,
							});
						})					
				} else {
					const { columns = [] } = template;
						columns.forEach((column = {}, index) => {
							const {
								action: {
									label,
									text,
									type,
									uri,
								} = {},
								imageUrl,
								aspectRatio,
							} = column;

							validCarouselImages.push({
								activeIndex: index,
								originalContentUrl: getCdnUrl({url: imageUrl, channelName: 'LINE', channelSubType: 'CARD'}),
								selectedActionType: type ? (type === MESSAGE_ACTION_TYPE ? TEXT_ACTION_TYPE : URL_ACTION_TYPE) : '',
								actionContent: text || uri,
								actionLabel: label,
								aspectRatio,
								type: CAROUSEL,
							});
						})
				}
				updateCarouselImage(validCarouselImages);
			}
		}
	}, [content]);

	const getFormattedCarouselMessagePayload = (newCarouselImages, inheritedMessageTitle, inheritedTitle) => {
		const existingMessageTitle = inheritedMessageTitle !== undefined ? inheritedMessageTitle : messageTitle;
		const existingTitle = inheritedTitle !== undefined ? inheritedTitle : altText;
		let isErrorIndex;
		const columns = [];
		(newCarouselImages || []).forEach(({
			originalContentUrl,
			aspectRatio = '1:1',
			selectedActionType,
			actionLabel,
			actionContent,
			actionContentErrorMessage,
			actionLabelErrorMessage,
			activeIndex,
		}) => {
			isErrorIndex = (isErrorIndex !== undefined && isErrorIndex !== false)
				? isErrorIndex
				: ((!originalContentUrl || !selectedActionType || actionContentErrorMessage || actionLabelErrorMessage || !actionContent) && activeIndex);
			columns.push({
				imageUrl: getCdnUrl({url: originalContentUrl, channelName: 'LINE', channelSubType: 'CARD'}),
				aspectRatio,
				action: {
					type: selectedActionType ? (selectedActionType === TEXT_ACTION_TYPE ? MESSAGE_ACTION_TYPE : URL_ACTION_TYPE) : '',
					label: actionLabel,
					[selectedActionType]: actionContent
				}
			});
		});

		const payload = {
			isError: isErrorIndex !== undefined && isErrorIndex !== false,
			messageTitle: existingMessageTitle,
			altText: existingTitle,
			type: FLEX,
			index,
		}

		if (columns.length) {
			payload.template = {
				columns,
				type: 'image_carousel',
			};
		} else {
			payload.isError = true;
		}
		payload.isError = payload.isError || (isFullMode ? !existingMessageTitle : false) || !existingTitle;
		updateMessageState(payload);
		return payload;
	}

	const updateCarouselMessageState = (config) => {
		const newCarouselImages = [...carouselImages];
		newCarouselImages.splice(config.activeIndex, 1, config);
		updateCarouselImage(newCarouselImages);
		getFormattedCarouselMessagePayload(newCarouselImages);
	}

	const addContent = () => {
		const newCarouselImages = [
			...carouselImages,
			{
				...defaultCarouselContent,
				activeIndex: carouselImages.length,
			},
		]
		updateCarouselImage(newCarouselImages);
		getFormattedCarouselMessagePayload(newCarouselImages);
	}

	const duplicateContent = () => {
		const contentToDuplicate = {
			...carouselImages[activeIndex],
			activeIndex: carouselImages.length,
		};
		const newCarouselImages = [
			...carouselImages,
			contentToDuplicate,
		];
		updateCarouselImage(newCarouselImages);
		getFormattedCarouselMessagePayload(newCarouselImages);
	}

	const shiftRightContent = () => {
		const newActiveIndex = Number(activeIndex) + 1;
		updateActiveIndex(`${newActiveIndex}`);
	}

	const shiftLeftContent = () => {
		const newActiveIndex = Number(activeIndex) - 1;
		updateActiveIndex(`${newActiveIndex}`);
	}

	const deleteContent = () => {
		const newCarouselImages = [...carouselImages];
		newCarouselImages.splice(activeIndex, 1);
		updateCarouselImage(newCarouselImages);
		getFormattedCarouselMessagePayload(newCarouselImages);

		const parsedActiveIndex = Number(activeIndex);
		const newActiveIndex = parsedActiveIndex === 0 ? parsedActiveIndex : parsedActiveIndex - 1;
		updateActiveIndex(`${newActiveIndex}`);
	}

	const onTabChange = (index) => {
		updateActiveIndex(index);
	}

	const operations = (
		<>
			<CapButton
				onClick={addContent}
				type="flat"
				disabled={MAX_CAROUSEL_ALLOWED === carouselImages.length}
				isAddBtn
				style={{ padding: 0, marginTop: 12 }}
			>
				<FormattedMessage {...messages.addCard} />
			</CapButton>
			<CapRow
				style={{
					position: 'absolute',
					top: 66,
					right: 0,
				}}
				className="extra-button-group"
				type='flex'
				gap={12}
			>
				<CapTooltip 
					title={<FormattedMessage {...messages.duplicateTooltipLabel} />}
				>
					<CapIcon
						type="copy"
						size="s"
						onClick={duplicateContent}
						disabled={MAX_CAROUSEL_ALLOWED === carouselImages.length}
					/>
				</CapTooltip>
				<CapTooltip 
					title={<FormattedMessage {...messages.shiftLeftTooltipLabel} />}
				>
					<CapIcon
						type="left"
						size="s"
						onClick={shiftLeftContent}
						disabled={defaultActiveIndex === Number(activeIndex)}
					/>
				</CapTooltip>
				<CapTooltip 
					title={<FormattedMessage {...messages.shiftRightTooltipLabel} />}
				>
					<CapIcon
						type="right"
						size="s"
						onClick={shiftRightContent}
						disabled={carouselImages.length === (Number(activeIndex) + 1)}
					/>
				</CapTooltip>
				<CapTooltip 
					title={<FormattedMessage {...messages.deleteTooltipLabel} />}
				>
					<CapIcon
						type="delete"
						size="s"
						onClick={deleteContent}
						disabled={1 === carouselImages.length}
					/>
				</CapTooltip>
			</CapRow>
		</>
	);

	const getTabPanes = () => {
		return carouselImages.map((carouselImage, index) => {
			const isSelected = Number(activeIndex) === index;
			return {
				key: `${index}`,
				tab: (
					<span
						style={{
							display: 'inline-block',
							borderRadius: '50%',
							color: CAP_WHITE,
							backgroundColor: !isSelected ? FONT_COLOR_02 : FONT_COLOR_01,
							height: CAP_SPACE_24,
							width: CAP_SPACE_24,
							textAlign: 'center',
							paddingTop: 2,
						}}
					>
						{index + 1}
					</span>
				),
				content: (
					<LineImageCarouselContent
						{...props}
						content={carouselImage}
						activeIndex={index}
						updateCarouselMessageState={updateCarouselMessageState}
					/>
				),
			}
		});
	};

	const onTextTitleChange = ({ target: { value } }) => {
		updateTextMessageTitle(value);
		let errorMessage = false;
		if (value === '') {
			errorMessage = formatMessage(messages.emptyTitleErrorMessage);
		}
		getFormattedCarouselMessagePayload(carouselImages, value);
		updateErrorMessageTitle(errorMessage);
	}

	  const onTitleChange = ({ target: { value } }) => {
    updateTitle(value);
    let errorMessage;
    if (value === '') {
        errorMessage = formatMessage(messages.emptyAltTextErrorMessage);
    }
		updateErrorTitle(errorMessage);
		getFormattedCarouselMessagePayload(carouselImages, undefined, value);
	
	}

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

		const cardDataList = [];
		lineTextTemplates.forEach(template => {
			let templateData = {};
			const {
				content: {
					messages: [{
						contents: imageCarouselContents,
						template: imageCarouselTemplate,
					}] = [{}],
				} = {},
			} = template.versions.base;
			let isNewLineFormat = false;
			if(!imageCarouselTemplate  && imageCarouselContents) {
				isNewLineFormat = true;
			}
			templateData.url = get(imageCarouselContents, 'contents.0.hero.url', '') || get(imageCarouselTemplate, 'columns.0.imageUrl', '');
			templateData.title = template.name;
			templateData.key = template.name;
			templateData.hoverOption = (
				<CapButton onClick={() => onTemplateSelection(template)}>
					<FormattedMessage {...messages.select} />
				</CapButton>
			);
			if (imageCarouselTemplate || imageCarouselContents) {
				cardDataList.push(templateData);
			}
		});
		return (
			<>
				<CapHeading type="h3" className="drawer-head">
					{formatMessage(messages.lineTemplateImage)}
				</CapHeading>
				<LineDrawer
					getAllTemplates={getAllTemplates}
					cardDataList={cardDataList}
					isDrawer={isTemplateDrawerRequired}
					Templates={Templates}
					searchPlaceholder={formatMessage(messages.searchImages)}
				/>
			</>
		);
	};

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

	const onTemplateSelection = (templateData) => {
		const template = get(templateData, 'versions.base.content.messages[0].template', {});
		const contents = get(templateData, 'versions.base.content.messages[0].contents', {});
		const altText = get(templateData, 'versions.base.content.messages[0].altText', '');
		let isNewLineFormat = false;
		const validCarouselImages = [];
		
		if (!isEmpty(contents) && isEmpty(template)) {
			isNewLineFormat = true;
		}
		if (isNewLineFormat) {
			const { contents : flexContents = [] } = contents;
			
				flexContents.forEach((content = {}, index) => {
					const {
						footer: {
							contents: [{
								action: {
									text = '',
									label = '',
									type: buttonType = '',
									uri,
								} = {},
							}] = [],
						} = {},
						hero: {
							url = '',
							aspectRatio = '',
						} = {},
					} = content || {};
					validCarouselImages.push({
						activeIndex: index,
						originalContentUrl: getCdnUrl({url: url, channelName: 'LINE', channelSubType: 'CARD'}),
						aspectRatio,
						selectedActionType: buttonType ? (buttonType === MESSAGE_ACTION_TYPE ? TEXT_ACTION_TYPE : URL_ACTION_TYPE) : '',
						actionContent: text || uri,
						actionLabel: label,
						type: CAROUSEL,
					});
				})					
		
		} else {
			const { columns } = template;
			if (columns && columns.length) {
				columns.forEach((column = {}, index) => {
					const {
						action: {
							label,
							text,
							type,
							uri,
						} = {},
						imageUrl,
					} = column;

					validCarouselImages.push({
						activeIndex: index,
						originalContentUrl: getCdnUrl({url: imageUrl, channelName: 'LINE', channelSubType: 'CARD'}),
						selectedActionType: type ? (type === MESSAGE_ACTION_TYPE ? TEXT_ACTION_TYPE : URL_ACTION_TYPE) : '',
						actionContent: text || uri,
						actionLabel: label,
						type: CAROUSEL,
					});
				})

			}		
		}
		updateCarouselImage(validCarouselImages);

		updateSelectedTemplate(template);
		updateTitle(altText);
		updateTemplateDrawerRequirement(false);
		updateCreateNew(true);
	}

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

	const getTemplateSection = () => {
		if (!isCreateNew) {
			return (
				<div className="form-builder-dragger" style={{
					textAlign: 'center',
					border: `1px dashed ${CAP_G06}`,
					minHeight: 120,
					padding: 60
				}}>
					<CapHeader
						className="choice-title"
						size="regular"
						title={formatMessage(messages.textMessageAddLabel)}
						style={{ marginBottom: 12 }}
					/>

					<CapButton
						className="dragger-button create-button"
						type="secondary"
						style={{ marginRight: CAP_SPACE_08 }}
						onClick={setNewContent}
						isAddBtn
					>
						<FormattedMessage {...messages.textMessageCreateNew} />
					</CapButton>

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

					<CapButton
						className="dragger-button select-template-button"
						type="secondary"
						style={{ marginLeft: CAP_SPACE_08 }}
						onClick={onSelectTemplate}
					>
						<FormattedMessage {...messages.textMessageSelectTemplate} />
					</CapButton>
				</div>
			)
		} else {
			return (
				<>
					<CapInput.TextArea
						maxLength={MAX_ALLOWED_TITLE_LENGTH}
						label={<FormattedMessage {...messages.titleLabel} />}
						inductiveText={<FormattedMessage {...messages.titleDescription} />}
						onChange={onTitleChange}
						value={altText}
						errorMessage={errorTitle}
						className="title-textarea"
					/>
					<CapTab
						defaultActiveKey={`${defaultActiveIndex}`}
						activeKey={activeIndex}
						tabBarExtraContent={operations}
						onChange={onTabChange}
						panes={getTabPanes()}
					/>
				</>
			);
		}
	}

	return (
		<div className={className}>
			<CapHeader
				title={(
					<>
						<span style={{ paddingRight: 6 }}>
							{formatMessage(messages.cardMessageTitle)}
						</span>
						<CapTooltipWithInfo title={formatMessage(messages.cardMessageInfo)} />
					</>
				)}
				size="regular"
				description={formatMessage(messages.cardMessageDescription)}
				className="card-message-header"
			/>
			{
				isFullMode
					? (
						<CapInput
							id={`${id}_input`}
							onChange={onTextTitleChange}
							errorMessage={errorMessageTitle}
							className="image-template-title"
							style={inheritedTitleStyle || {}}
							placeholder={formatMessage(messages.textMessageTitlePlaceholder)}
							defaultValue={messageTitle || ''}
							value={messageTitle || ''}
							size="default"
							label={formatMessage(messages.textMessageTitleLabel)}
						/>
					)
					: null
			}
			{getTemplateSection()}
			<CapDrawer
				content={getLineImageDrawerContent()}
				visible={isTemplateDrawerRequired}
				width={624}
				onClose={() => updateTemplateDrawerRequirement(false)}
			/>
		</div>

	)
}

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