import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { ajaxPost } from '../api/ajax';
import { useSettings } from '../contexts/SettingsContext';
import { useNotices } from '../contexts/NoticesContext';
import { getAdminPageUrl, getLimit, getPublicUrl, isPluginReady, isVendorPage } from '../Helpers';
import { showUpgradePopup } from '../utils/upgrade';
import HelpTooltip from '../components/HelpTooltip';
import WarningIcon from '../components/WarningIcon';

const TEXT_DOMAIN = 'stock-sync-with-google-sheet-for-woocommerce';

// Same check as the legacy isSheetSelected getter: an https docs.google.com URL and a tab name.
const isSheetSelected = ( url, tab ) => {
	if ( url ) {
		try {
			const parsed = new window.URL( url );
			if ( parsed.protocol !== 'https:' || parsed.hostname !== 'docs.google.com' ) {
				return false;
			}
		} catch ( error ) {
			return false;
		}
	}
	return !! tab;
};

/**
 * Dashboard tab (port of the removed templates/dashboard/overview.php).
 */
const Dashboard = () => {
	const { options, isPro } = useSettings();
	const notices = useNotices();
	const [ changingSetup, setChangingSetup ] = useState( false );
	const ready = isPluginReady();
	const vendor = isVendorPage();
	const limit = getLimit();
	const canChangeSetup = isSheetSelected( options.spreadsheet_url, options.sheet_tab );
	const publicUrl = getPublicUrl();

	// Legacy behaviour: send the wizard back to step 2 and reload into it.
	const changeSetup = async () => {
		if ( ! canChangeSetup || changingSetup ) {
			return;
		}
		setChangingSetup( true );
		try {
			await ajaxPost( 'ssgsw_update_options', { options: { setup_step: 2 } } );
			window.location.reload();
		} catch ( error ) {
			setChangingSetup( false );
			notices.error( __( 'FlexStock: Something went wrong', TEXT_DOMAIN ) );
		}
	};

	return (
		<div className="ssgs-dashboard__tab bounceInLeft active">
			<div className="ssgs-admin">
				<div className="ssgs-welcome">
					<div className="ssgs-welcome__left">
						<figure className="media float-left">
							<img src={ `${ publicUrl }/images/sync.svg` } alt="" />
						</figure>

						<div className="text">
							<h3 className="sub-title">
								{ ready ? (
									<span>
										{ __( 'Congratulations', TEXT_DOMAIN ) }{ ' ' }
										<img src={ `${ publicUrl }/images/congratulation.svg` } alt={ __( 'Congratulations', TEXT_DOMAIN ) } />
									</span>
								) : (
									<span>{ __( 'Setup is not complete', TEXT_DOMAIN ) }</span>
								) }
							</h3>
							<h2 className="title">
								{ ready ? __( 'Your products are syncing', TEXT_DOMAIN ) : __( 'Your products are NOT syncing!', TEXT_DOMAIN ) }
							</h2>
							{ ready ? (
								<a target="_blank" rel="noreferrer" href={ options.spreadsheet_url } className="ssgs-btn">
									{ __( 'View products on Google Sheet', TEXT_DOMAIN ) }
								</a>
							) : (
								<a href={ getAdminPageUrl() } className="ssgs-btn">
									{ __( 'Complete setup', TEXT_DOMAIN ) }
								</a>
							) }
						</div>
					</div>

					<div className="ssgs-welcome__right">
						{ vendor ? (
							<p>
								You can sync <strong>all products </strong> with your current setup.
							</p>
						) : (
							<>
								<p>
									<span className="ssgs-badge aliceblue flex-button">
										{ limit ? (
											<span className="flex-button">
												<WarningIcon />
												{ __( 'Only', TEXT_DOMAIN ) }
											</span>
										) : null }{ ' ' }
										<strong>
											{ limit || 'All' } { __( 'products', TEXT_DOMAIN ) }
										</strong>{ ' ' }
										{ __( 'can be synced with your current plan', TEXT_DOMAIN ) }
									</span>
								</p>
								{ ! isPro && (
									<p>
										<button type="button" className="pro-link ssgsw-promo gradient-text icon-inside ssgsw-react-link-button" onClick={ showUpgradePopup }>
											<img src={ `${ publicUrl }images/gift.svg` } alt="" />
											{ __( 'Unlock premium features', TEXT_DOMAIN ) }
										</button>
									</p>
								) }
							</>
						) }
					</div>
				</div>
			</div>

			<div className="ssgs-admin">
				<div className="ssgs-change-setup">
					<div className="ssgs-row">
						<div className="ssgs-column">
							<div className="form-group">
								<label htmlFor="ssgsw_dashboard_sheet_url" className="title title-secondary">
									{ __( 'Google Sheet URL', TEXT_DOMAIN ) }{ ' ' }
									<HelpTooltip position="bottom" image={ `${ publicUrl }/images/tooltip/step2_add-google-sheet-url.png` } />
								</label>
								<input
									type="url"
									id="ssgsw_dashboard_sheet_url"
									name="google_spreadsheet_url"
									readOnly
									value={ options.spreadsheet_url || '' }
									className="ssgs-input"
									placeholder={ __( 'Enter your google sheet URL', TEXT_DOMAIN ) }
								/>
							</div>
						</div>

						<div className="ssgs-column">
							<div className="form-group">
								<label htmlFor="ssgsw_dashboard_sheet_tab" className="title title-secondary">
									{ __( 'Sheet tab name ', TEXT_DOMAIN ) }{ ' ' }
									<HelpTooltip position="left bottom" image={ `${ publicUrl }/images/tooltip/step2_enter-sheet-tab-name.png` } />
								</label>
								<input
									type="text"
									id="ssgsw_dashboard_sheet_tab"
									readOnly
									value={ options.sheet_tab || '' }
									className="ssgs-input"
									placeholder={ __( 'Enter your google sheet Name', TEXT_DOMAIN ) }
								/>
							</div>
						</div>
					</div>
					<div className="form-group mb-0 text-center">
						<button
							type="button"
							className={ `ssgs-btn border${ canChangeSetup && ! changingSetup ? '' : ' disabled' }` }
							onClick={ changeSetup }
							disabled={ ! canChangeSetup || changingSetup }
							aria-busy={ changingSetup }
						>
							{ __( 'Change setup', TEXT_DOMAIN ) }
						</button>
					</div>
				</div>

				{ ! isPro && <hr /> }

				{ ! vendor && ! isPro && (
					<div className="ssgs-features">
						<div className="ssgs-row">
							<div className="ssgs-column">
								<div className="content">
									<h3 className="title">{ __( 'Unleash the true power', TEXT_DOMAIN ) }</h3>
									<ul>
										<li>{ __( 'You add products from Google Sheet', TEXT_DOMAIN ) }</li>
										<li>{ __( 'Description column to show the product description inside Google Sheet', TEXT_DOMAIN ) }</li>
										<li>{ __( 'Show the category of the product in a column on the Google Sheets', TEXT_DOMAIN ) }</li>
										<li>{ __( 'Show the sales count in a column on the Google Sheets', TEXT_DOMAIN ) }</li>
									</ul>
									<button type="button" className="ssgs-btn ssgsw-promo" onClick={ showUpgradePopup }>
										{ __( 'Unlock all features', TEXT_DOMAIN ) }
									</button>
								</div>
							</div>

							<div className="ssgs-column">
								<figure className="media text-center">
									<img src={ `${ publicUrl }/images/features.svg` } alt="" />
								</figure>
							</div>
						</div>
					</div>
				) }
			</div>
		</div>
	);
};

export default Dashboard;
