import React from 'react';
import { __ } from '@wordpress/i18n';
import Button from '../../../components/button';
import classnames from 'classnames';
import AccordionItem from '../../../components/accordion-item';
import AccordionItemOpenIndicator from '../../../components/accordion-item-open-indicator';
import RequestUtil from '../../../utils/request-util';
import ConfigValues from '../../../es6/config-values';
import update from 'immutability-helper';
import GutenbergEditor from '../../../es6/gutenberg-editor';
import ClassicEditor from '../../../es6/classic-editor';
import GutenbergReadabilityFleschPanel from '../../sidebar/panels/readability/GutenbergReadabilityFleschPanel';

export default class ReadabilityAnalysisContent extends React.Component {
	static defaultProps = {
		ignored: false,
		state: '',
		useReactAccordion: false,
	};

	constructor(props) {
		super(props);

		this.state = {
			ignored: !!props.ignored,
			checks: {
				readability: {
					ignored: !!props.ignored,
				},
			},
		};

		// Check if Gutenberg is active.
		if (ConfigValues.get_bool('gutenberg_active', 'metabox')) {
			this.editor = new GutenbergEditor();
		} else {
			this.editor = new ClassicEditor();
		}
	}

	componentDidUpdate(prevProps) {
		// Keep local ignored state in sync with upstream updates (e.g. refresh).
		if (prevProps.ignored !== this.props.ignored) {
			const ignored = !!this.props.ignored;
			this.setState({
				ignored,
				checks: update(this.state.checks, {
					readability: { ignored: { $set: ignored } },
				}),
			});
		}
	}

	componentWillUnmount() {
		// Clean up editor instance
		if (this.editor && typeof this.editor.destroy === 'function') {
			this.editor.destroy();
		}
	}

	levelsMap() {
		const veryEasy = __('Very easy to read', 'smartcrawl-seo'),
			easy = __('Easy to read', 'smartcrawl-seo'),
			fairlyEasy = __('Fairly easy to read', 'smartcrawl-seo'),
			plain = __('Standard', 'smartcrawl-seo'),
			fairlyDifficult = __('Fairly difficult to read', 'smartcrawl-seo'),
			difficult = __('Difficult to read', 'smartcrawl-seo'),
			confusing = __('Very difficult to read', 'smartcrawl-seo'),
			easyTag = __('Easy', 'smartcrawl-seo'),
			plainTag = __('Standard', 'smartcrawl-seo'),
			difficultTag = __('Difficult', 'smartcrawl-seo'),
			fairlyDifficultTag = __('Fairly difficult', 'smartcrawl-seo');

		const map = {};

		map[veryEasy] = {
			min: 90,
			max: 100,
			tag: easyTag,
		};
		map[easy] = {
			min: 80,
			max: 89.9,
			tag: easyTag,
		};
		map[fairlyEasy] = {
			min: 70,
			max: 79.9,
			tag: easyTag,
		};
		map[plain] = {
			min: 60,
			max: 69.9,
			tag: plainTag,
		};
		map[fairlyDifficult] = {
			min: 50,
			max: 59.9,
			tag: fairlyDifficultTag,
		};
		map[difficult] = {
			min: 30,
			max: 49.9,
			tag: difficultTag,
		};
		map[confusing] = {
			min: 0,
			max: 29.9,
			tag: difficultTag,
		};

		return map;
	}

	handleIgnore() {
		const id = 'readability';

		RequestUtil.post(
			'wds_analysis_ignore_check',
			ConfigValues.get('nonce', 'metabox'),
			{
				post_id: this.editor.get_data().get_id(),
				check_id: id,
			}
		).then(() => {
			this.setState({
				ignored: true,
				checks: update(this.state.checks, {
					[id]: { ignored: { $set: true } },
				}),
			});
		});
	}

	handleUnignore() {
		const id = 'readability';

		RequestUtil.post(
			'wds_analysis_unignore_check',
			ConfigValues.get('nonce', 'metabox'),
			{
				post_id: this.editor.get_data().get_id(),
				check_id: id,
			}
		).then(() => {
			this.setState({
				ignored: false,
				checks: update(this.state.checks, {
					[id]: { ignored: { $set: false } },
				}),
			});
		});
	}

	renderFleschExpandedBody() {
		return (
			<React.Fragment>
				<strong>{__('Overview', 'smartcrawl-seo')}</strong>
				<p className="sui-description">
					{__(
						'The Flesch-Kincaid readability tests are readability tests designed to indicate how difficult a passage is to understand. Here are the benchmarks.',
						'smartcrawl-seo'
					)}
				</p>
				{this.renderLevels()}

				<strong>{__('How to fix', 'smartcrawl-seo')}</strong>
				<p className="sui-description">
					{__(
						'Try to use shorter sentences, with less difficult words to improve readability.',
						'smartcrawl-seo'
					)}
				</p>

				<div className="wds-ignore-container">
					<Button
						className="wds-ignore"
						color="ghost"
						icon="sui-icon-eye-hide"
						text={__('Ignore', 'smartcrawl-seo')}
						onClick={() => this.handleIgnore()}
					/>

					<span className="sui-description">
						{__(
							'This will ignore warnings for this particular post.',
							'smartcrawl-seo'
						)}
					</span>
				</div>
			</React.Fragment>
		);
	}

	renderLevels() {
		const { useReactAccordion } = this.props;

		const table = (
			<table
				className={
					useReactAccordion
						? 'sui-table wds-readability-levels-table'
						: 'sui-table'
				}
			>
				<thead>
					<tr>
						<th>{__('Score', 'smartcrawl-seo')}</th>
						<th>{__('Description', 'smartcrawl-seo')}</th>
					</tr>
				</thead>

				<tbody>
					{Object.keys(this.levelsMap()).map((label, index) => {
						const lvMap = this.levelsMap()[label];

						return (
							<tr key={index}>
								<td>
									{Math.ceil(lvMap.min)}
									{' - '}
									{Math.ceil(lvMap.max)}
								</td>
								<td>{label}</td>
							</tr>
						);
					})}
				</tbody>
			</table>
		);

		if (useReactAccordion) {
			return (
				<div className="wds-readability-levels-table-wrap">{table}</div>
			);
		}

		return table;
	}

	render() {
		const { state, level, useReactAccordion } = this.props;
		const { ignored } = this.state;

		if (useReactAccordion) {
			return (
				<div className="wds-report-inner">
					<div className="wds-seo-assessments-stack">
						<GutenbergReadabilityFleschPanel
							state={state}
							ignored={ignored}
							level={level}
							onIgnore={() => this.handleIgnore()}
							onUnignore={() => this.handleUnignore()}
						>
							{this.renderFleschExpandedBody()}
						</GutenbergReadabilityFleschPanel>
					</div>
				</div>
			);
		}

		return (
			<div className="wds-report-inner">
				<div className="wds-accordion sui-accordion">
					<AccordionItem
						className={classnames(
							'wds-check-item',
							`sui-${state}`,
							`wds-check-${state}`,
							{ disabled: !!ignored }
						)}
						header={
							<React.Fragment>
								<div className="sui-accordion-item-title sui-accordion-col-8">
									<span
										aria-hidden="true"
										className={classnames(
											`sui-${state}`,
											state === 'success'
												? 'sui-icon-check-tick'
												: 'sui-icon-info'
										)}
									></span>
									{__(
										'Flesch-Kincaid Test',
										'smartcrawl-seo'
									)}
								</div>

								<div className="sui-accordion-col-4">
									{ignored ? (
										<Button
											className="wds-unignore"
											color="ghost"
											icon="sui-icon-undo"
											text={__(
												'Restore',
												'smartcrawl-seo'
											)}
											onClick={() =>
												this.handleUnignore()
											}
										/>
									) : (
										<React.Fragment>
											<span
												className={classnames(
													'sui-tag',
													`sui-tag-${state}`
												)}
											>
												{level}
											</span>
											<AccordionItemOpenIndicator />
										</React.Fragment>
									)}
								</div>
							</React.Fragment>
						}
					>
						{this.renderFleschExpandedBody()}
					</AccordionItem>
				</div>
			</div>
		);
	}
}
