import { useEffect, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { ajaxPost } from '../../api/ajax';
import { useSettings } from '../../contexts/SettingsContext';
import { useNotices } from '../../contexts/NoticesContext';
import { getSiteAttributes, isTrue, isVendorPage } from '../../Helpers';
import useSheetSync from '../../hooks/useSheetSync';
import { VendorPopupContext } from '../../hooks/useProGate';
import Modal from '../../components/Modal';
import SyncProgress from '../../components/SyncProgress';
import SyncSettingsSection from './SyncSettingsSection';
import PreferenceSection from './PreferenceSection';
import ColumnsSection from './ColumnsSection';

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

// The option keys the legacy save_checkbox_settings() sent, in the same order.
const SAVED_KEYS = [
	'add_products_from_sheet',
	'show_sku',
	'show_short_description',
	'show_attributes',
	'show_total_sales',
	'show_product_category',
	'show_custom_meta_fileds',
	'show_custom_fileds',
	'show_product_images',
	'show_product_gallery',
	'product_gallery_column_count',
	'bulk_edit_option',
	'formula_active',
	'show_product_url',
	'show_long_description',
	'show_product_status',
	'show_product_status_data',
	'show_product_tags',
	'show_product_image_alt',
	'show_upsell_ids',
	'show_crosssell_ids',
	'show_custom_badge',
	'show_product_brand',
	'all_product_filter_info',
	'filter_active',
	'shop_name_sync',
	'separate_attributes',
	'allowed_attributes',
	'skipped_attributes',
	'selected_sync_mode',
	'live_sync_direction',
	'peroidic_sync_direction',
	'cron_perdic_sync',
	'cron_formula_perdic_sync',
	'perdic_sync_day',
	'perdic_formula_sync_day',
	'perdic_sync_time',
	'perdic_formula_sync_time',
	'save_and_sync',
];

// Legacy x-init on the attribute list: a null allow-list starts as "every attribute not skipped".
const initialAllowedAttributes = ( options ) => {
	const slugs = getSiteAttributes().map( ( attribute ) => attribute.slug );
	const skipped = Array.isArray( options.skipped_attributes ) ? options.skipped_attributes : [];
	return skipped.length ? slugs.filter( ( slug ) => ! skipped.includes( slug ) ) : slugs;
};

/**
 * Settings tab (port of the removed templates/dashboard/settings.php).
 */
const Settings = () => {
	const { options, changeCount, updateOption, applySavedOptions, commitSaved, discardChanges } = useSettings();
	const notices = useNotices();
	const { syncing, progress, title: syncTitle, runSync } = useSheetSync( 'settings' );
	const [ saving, setSaving ] = useState( false );
	const [ confirmDiscard, setConfirmDiscard ] = useState( false );
	const [ vendorPopup, setVendorPopup ] = useState( false );

	useEffect( () => {
		if ( options.allowed_attributes === null || options.allowed_attributes === undefined ) {
			applySavedOptions( { allowed_attributes: initialAllowedAttributes( options ) } );
		}
		// Run once on mount, like the legacy x-init.
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [] );

	const save = async () => {
		if ( saving ) {
			return;
		}
		setSaving( true );

		const values = { ...options, save_and_sync: ! isTrue( options.save_and_sync ) };
		const payload = SAVED_KEYS.reduce( ( result, key ) => ( { ...result, [ key ]: values[ key ] } ), {} );

		try {
			const response = await ajaxPost( 'ssgsw_update_options', { options: payload } );
			if ( ! response.success ) {
				notices.error( __( 'Oops, settings save failed!', TEXT_DOMAIN ) );
				return;
			}

			// Settings are stored now; the sheet rebuild below reports its own result.
			commitSaved( values );
			await runSync();
		} catch ( error ) {
			notices.error( __( 'Unexpected error occurred!', TEXT_DOMAIN ) );
		} finally {
			setSaving( false );
		}
	};

	const discard = () => {
		discardChanges();
		setConfirmDiscard( false );
	};

	return (
		<VendorPopupContext.Provider value={ () => setVendorPopup( true ) }>
			<div className="ssgs-dashboard__tab bounceInRight active">
				<div className="ssgs-admin ssgsw-settings">
					{ ! isVendorPage() && <SyncSettingsSection /> }
					<PreferenceSection filters={ options.all_product_filter_info || [] } onFiltersChange={ ( rows ) => updateOption( 'all_product_filter_info', rows ) } />
					<ColumnsSection />

					{ changeCount > 0 && (
						<div className="ssgsw_button_container" role="region" aria-label={ __( 'Unsaved changes', TEXT_DOMAIN ) }>
							<span className="screen-reader-text" aria-live="polite">
								{ __( 'You have unsaved changes.', TEXT_DOMAIN ) }
							</span>
							<button type="button" onClick={ save } disabled={ saving } aria-busy={ saving } className="ssgsw_save_button">
								{ saving ? __( 'Saving...', TEXT_DOMAIN ) : __( 'Save & Sync', TEXT_DOMAIN ) }
							</button>
							<button type="button" className="ssgsw_save_close" onClick={ () => setConfirmDiscard( true ) } disabled={ saving }>
								{ __( 'Discard Changes', TEXT_DOMAIN ) }
							</button>
						</div>
					) }
				</div>
			</div>

			{ confirmDiscard && (
				<Modal
					onClose={ () => setConfirmDiscard( false ) }
					renderTitle={ ( id ) => (
						<>
							<button type="button" className="close ssgs_close_button" onClick={ () => setConfirmDiscard( false ) } aria-label={ __( 'Close', TEXT_DOMAIN ) }>
								&times;
							</button>
							<div className="profile-section">
								<div className="profile-image ssgsw_logo_section_popup">
									<span className="dashicons dashicons-warning ssgs_warning" aria-hidden="true"></span>
								</div>
								<div className="profile-details">
									<h3 id={ id } className="profile-title">
										{ __( 'Discard All Changes', TEXT_DOMAIN ) }
									</h3>
									<p className="profile-description">
										{ __(
											'You are about to discard all unsaved changes. All of your settings will be reset to the point where you last saved. Are you sure you want to do this?',
											TEXT_DOMAIN
										) }
									</p>
								</div>
							</div>
						</>
					) }
				>
					<div className="ssgs_first_section">
						<div className="ssgs_button_section">
							<button type="button" className="ssgsw_save_close1" onClick={ () => setConfirmDiscard( false ) }>
								{ __( 'No, continue editing', TEXT_DOMAIN ) }
							</button>
							<button type="button" className="ssgsw_save_changes" onClick={ discard }>
								{ __( 'Yes, discard changes', TEXT_DOMAIN ) }
							</button>
						</div>
					</div>
				</Modal>
			) }

			{ vendorPopup && (
				<Modal
					onClose={ () => setVendorPopup( false ) }
					renderTitle={ ( id ) => (
						<>
							<button type="button" className="close ssgs_close_button" onClick={ () => setVendorPopup( false ) } aria-label={ __( 'Close', TEXT_DOMAIN ) }>
								&times;
							</button>
							<div className="ssgs_first_section">
								<p id={ id }>{ __( 'Contact admin to enable this feature', TEXT_DOMAIN ) }</p>
							</div>
						</>
					) }
				/>
			) }

			{ syncing && <SyncProgress title={ syncTitle } progress={ progress } /> }
		</VendorPopupContext.Provider>
	);
};

export default Settings;
