import { createInterpolateElement, useRef, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { useNotices } from '../../contexts/NoticesContext';
import { getPublicUrl } from '../../Helpers';
import HelpTooltip from '../../components/HelpTooltip';
import VideoPlayer from '../../components/VideoPlayer';
import Pane, { animationClass } from './Pane';

const TEXT_DOMAIN = 'stock-sync-with-google-sheet-for-woocommerce';
const REQUIRED_KEYS = [ 'client_email', 'private_key', 'type', 'project_id', 'client_id' ];

/**
 * Step 1: credentials upload (screen 1) and "Enable Google Sheet API" (screen 2).
 * The drop zone replaces FilePond but keeps its classes and the same validation.
 */
const Step1Credentials = ( { isFirstScreen, direction, credentialFile, onCredentials, enabledApi, onEnabledApiChange } ) => {
	const notices = useNotices();
	const inputRef = useRef( null );
	const [ dragging, setDragging ] = useState( false );
	const animation = animationClass( direction );

	const rejectFile = ( title, content ) => {
		notices.alert( 'error', title, content );
		if ( inputRef.current ) {
			inputRef.current.value = '';
		}
	};

	const readFile = ( file ) => {
		if ( ! file ) {
			return;
		}

		if ( file.type !== 'application/json' ) {
			rejectFile(
				__( 'FlexStock: Ops! Invalid file type', TEXT_DOMAIN ),
				__( 'FlexStock: Only valid JSON file with valid Google Service Account Credential is allowed', TEXT_DOMAIN )
			);
			return;
		}

		const reader = new window.FileReader();
		reader.onload = ( event ) => {
			let data = null;
			try {
				data = JSON.parse( event.target.result );
			} catch ( error ) {
				data = null;
			}

			if ( ! data || REQUIRED_KEYS.some( ( key ) => ! data[ key ] ) ) {
				rejectFile( __( 'FlexStock: Invalid credentials', TEXT_DOMAIN ) );
				return;
			}

			if ( inputRef.current ) {
				inputRef.current.value = '';
			}
			onCredentials( data, file.name );
		};
		reader.readAsText( file );
	};

	return (
		<Pane direction={ direction }>
			{ isFirstScreen ? (
				<div className={ `ssgs-credential active${ animation }` }>
					<div className="entry-title text-center">
						<h3 className="title">
							{ __( 'Add Credentials', TEXT_DOMAIN ) }{ ' ' }
							<HelpTooltip
								position="bottom"
								text={ __( 'Adding credential here will allow you to sync your store products within seconds from Google Sheets.', TEXT_DOMAIN ) }
							/>
						</h3>
						{ /* Same separate strings as step-1.php so existing translations still apply. */ }
						<p className="description credential">
							{ __( 'Create a', TEXT_DOMAIN ) } <strong>{ __( 'Service Account', TEXT_DOMAIN ) }</strong>{ ' ' }
							{ __( 'from your', TEXT_DOMAIN ) }{ ' ' }
							<a target="_blank" rel="noreferrer" href="https://console.cloud.google.com/apis/credentials">
								<span className="ssgs-link">{ __( 'Google Cloud Platform', TEXT_DOMAIN ) }</span>
							</a>{ ' ' }
							{ __( 'and download the', TEXT_DOMAIN ) }{ ' ' }
							<strong>
								<i>credentials.json</i>
							</strong>{ ' ' }
							{ __( 'file', TEXT_DOMAIN ) }
						</p>
					</div>

					<div className="ssgs-row align-items-center">
						<div className="ssgs-column">
							<div className="upload-credentials">
								<div
									className={ `filepond--root ssgsw-dropzone${ dragging ? ' is-dragging' : '' }` }
									onDragOver={ ( event ) => {
										event.preventDefault();
										setDragging( true );
									} }
									onDragLeave={ () => setDragging( false ) }
									onDrop={ ( event ) => {
										event.preventDefault();
										setDragging( false );
										readFile( event.dataTransfer.files[ 0 ] );
									} }
								>
									<div className="filepond--drop-label">
										<label htmlFor="credentialjson">
											<div className="ssgs-upload">
												<div>
													{ createInterpolateElement( __( 'Drag and drop the <strong><i>credential.json</i></strong> file here', TEXT_DOMAIN ), {
														strong: <strong />,
														i: <i />,
													} ) }
												</div>
												<span>{ __( 'OR', TEXT_DOMAIN ) }</span>
												<div>
													<span className="upload-button">{ __( 'Upload file', TEXT_DOMAIN ) }</span>
												</div>
												{ credentialFile && (
													<div className="ssgs-uploaded-file-name">
														<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 16 16" aria-hidden="true">
															<path d="M10.97 4.97a.75.75 0 0 1 1.07 1.05l-3.99 4.99a.75.75 0 0 1-1.08.02L4.324 8.384a.75.75 0 1 1 1.06-1.06l2.094 2.093 3.473-4.425a.267.267 0 0 1 .02-.022z" />
														</svg>{ ' ' }
														<i>{ credentialFile }</i> { __( 'Uploaded', TEXT_DOMAIN ) }
													</div>
												) }
											</div>
										</label>
										<input
											ref={ inputRef }
											type="file"
											id="credentialjson"
											accept="application/json"
											className="screen-reader-text"
											onChange={ ( event ) => readFile( event.target.files[ 0 ] ) }
										/>
									</div>
								</div>
							</div>
						</div>

						<div className="ssgs-column">
							<VideoPlayer
								title={ __( 'How to add Credentials?', TEXT_DOMAIN ) }
								duration="1:46"
								videoId="6yZAQQMBq6M"
								thumbnail={ `${ getPublicUrl() }/images/thumbnails/credentials.png` }
							/>
						</div>
					</div>
				</div>
			) : (
				<div className={ `enable-google-api active${ animation }` }>
					<div className="ssgs-row align-items-center">
						<div className="ssgs-column">
							<div className="entry-title enable-api-content">
								<h3 className="title">
									{ __( 'Enable Google Sheet API', TEXT_DOMAIN ) }{ ' ' }
									<HelpTooltip position="bottom" image={ `${ getPublicUrl() }/images/tooltip/step1_api-enable-api.gif` } />
								</h3>
								<p className="description">
									<span className="serial-number">1</span>
									<a target="_blank" rel="noreferrer" className="ssgs-link" href="https://console.cloud.google.com/apis/library/sheets.googleapis.com">
										{ __( 'Click here', TEXT_DOMAIN ) }
									</a>{ ' ' }
									{ __( 'to enable Google Sheet API', TEXT_DOMAIN ) } { __( 'Visit the link and enable Google Sheets API', TEXT_DOMAIN ) }{ ' ' }
									{ __( 'by clicking the', TEXT_DOMAIN ) } <span className="label-with-bg">{ __( 'ENABLE', TEXT_DOMAIN ) }</span>{ ' ' }
									{ __( 'button as shown in the image', TEXT_DOMAIN ) }
								</p>
							</div>
						</div>
						<div className="ssgs-column">
							<img src={ `${ getPublicUrl() }images/setup/enable-google-sheet-api.svg` } width="415" alt="" />
						</div>
					</div>

					<div className="form-group">
						<label htmlFor="enable_google_api">
							<input
								type="checkbox"
								id="enable_google_api"
								name="enable_google_api"
								checked={ enabledApi }
								onChange={ ( event ) => onEnabledApiChange( event.target.checked ) }
							/>
							{ __( 'I’ve enabled Google Sheet API', TEXT_DOMAIN ) }
						</label>
					</div>
				</div>
			) }
		</Pane>
	);
};

export default Step1Credentials;
