/**
 * Wizard step 1: pick/create a supplier, drop a file, upload it.
 */

import { useEffect, useState } from '@wordpress/element';
import {
	Button,
	Notice,
	SelectControl,
	TextControl,
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';

import { createJob, listSuppliers } from '../api';

const SAMPLE_SUPPLIER_NAME = __( 'Sample supplier', 'emberprice' );

export default function UploadStep( { onUploaded } ) {
	const [ suppliers, setSuppliers ] = useState( [] );
	const [ supplierMode, setSupplierMode ] = useState( 'existing' );
	const [ supplierId, setSupplierId ] = useState( '' );
	const [ supplierName, setSupplierName ] = useState( '' );
	const [ file, setFile ] = useState( null );
	const [ progress, setProgress ] = useState( 0 );
	const [ isUploading, setIsUploading ] = useState( false );
	const [ isLoadingSample, setIsLoadingSample ] = useState( false );
	const [ error, setError ] = useState( '' );

	useEffect( () => {
		listSuppliers()
			.then( setSuppliers )
			.catch( () => setSuppliers( [] ) );
	}, [] );

	const handleFileChange = ( event ) => {
		setFile( event.target.files[ 0 ] || null );
		setError( '' );
	};

	const handleDrop = ( event ) => {
		event.preventDefault();
		const dropped = event.dataTransfer.files[ 0 ];

		if ( dropped ) {
			setFile( dropped );
			setError( '' );
		}
	};

	const canSubmit =
		null !== file &&
		! isUploading &&
		! isLoadingSample &&
		( ( 'existing' === supplierMode && '' !== supplierId ) ||
			( 'new' === supplierMode && '' !== supplierName.trim() ) );

	const handleSubmit = () => {
		setError( '' );
		setIsUploading( true );
		setProgress( 0 );

		createJob( {
			file,
			supplierId: 'existing' === supplierMode ? supplierId : null,
			supplierName: 'new' === supplierMode ? supplierName.trim() : null,
			onProgress: setProgress,
		} )
			.then( ( result ) => {
				setIsUploading( false );
				onUploaded( result );
			} )
			.catch( ( uploadError ) => {
				setIsUploading( false );
				setError(
					uploadError?.message ||
						__(
							'Something went wrong uploading the file.',
							'emberprice'
						)
				);
			} );
	};

	const handleTrySample = () => {
		setError( '' );
		setIsLoadingSample( true );

		fetch( window.embpSettings.sampleFileUrl )
			.then( ( response ) => response.blob() )
			.then( ( blob ) => {
				const sampleFile = new File(
					[ blob ],
					window.embpSettings.sampleFileName,
					{
						type: 'text/csv',
					}
				);
				const existingSample = suppliers.find(
					( supplier ) => supplier.name === SAMPLE_SUPPLIER_NAME
				);

				setIsLoadingSample( false );
				setIsUploading( true );
				setProgress( 0 );

				createJob( {
					file: sampleFile,
					supplierId: existingSample ? existingSample.id : null,
					supplierName: existingSample ? null : SAMPLE_SUPPLIER_NAME,
					onProgress: setProgress,
				} )
					.then( ( result ) => {
						setIsUploading( false );
						onUploaded( result );
					} )
					.catch( ( uploadError ) => {
						setIsUploading( false );
						setError(
							uploadError?.message ||
								__(
									'Something went wrong uploading the file.',
									'emberprice'
								)
						);
					} );
			} )
			.catch( () => {
				setIsLoadingSample( false );
				setError(
					__( 'Could not load the sample file.', 'emberprice' )
				);
			} );
	};

	return (
		<div className="embp-upload-step">
			{ error && (
				<Notice status="error" isDismissible={ false }>
					{ error }
				</Notice>
			) }

			<div className="embp-upload-sample">
				<p>
					{ __(
						'New here? Try the full flow with a bundled sample price list, or download it to see the expected format.',
						'emberprice'
					) }
				</p>
				<Button
					variant="secondary"
					isBusy={ isLoadingSample }
					disabled={ isLoadingSample || isUploading }
					onClick={ handleTrySample }
				>
					{ isLoadingSample
						? __( 'Loading sample data…', 'emberprice' )
						: __( 'Try with sample data', 'emberprice' ) }
				</Button>
				<a
					className="embp-upload-sample__download"
					href={ window.embpSettings.sampleFileUrl }
					download={ window.embpSettings.sampleFileName }
				>
					{ __( 'Download sample file', 'emberprice' ) }
				</a>
			</div>

			<div className="embp-supplier-picker">
				<div className="embp-supplier-picker__modes">
					<label htmlFor="embp-supplier-existing">
						<input
							id="embp-supplier-existing"
							name="embp-supplier-mode"
							type="radio"
							checked={ 'existing' === supplierMode }
							onChange={ () => setSupplierMode( 'existing' ) }
						/>
						{ __( 'Existing supplier', 'emberprice' ) }
					</label>
					<label htmlFor="embp-supplier-new">
						<input
							id="embp-supplier-new"
							name="embp-supplier-mode"
							type="radio"
							checked={ 'new' === supplierMode }
							onChange={ () => setSupplierMode( 'new' ) }
						/>
						{ __( 'New supplier', 'emberprice' ) }
					</label>
				</div>

				{ 'existing' === supplierMode ? (
					<SelectControl
						label={ __( 'Supplier', 'emberprice' ) }
						value={ supplierId }
						options={ [
							{
								label: __( 'Select a supplier…', 'emberprice' ),
								value: '',
							},
							...suppliers.map( ( supplier ) => ( {
								label: supplier.name,
								value: String( supplier.id ),
							} ) ),
						] }
						onChange={ setSupplierId }
						__next40pxDefaultSize
						__nextHasNoMarginBottom
					/>
				) : (
					<TextControl
						label={ __( 'New supplier name', 'emberprice' ) }
						value={ supplierName }
						onChange={ setSupplierName }
						__next40pxDefaultSize
						__nextHasNoMarginBottom
					/>
				) }
			</div>

			<div
				className="embp-dropzone"
				onDragOver={ ( event ) => event.preventDefault() }
				onDrop={ handleDrop }
			>
				<input
					type="file"
					accept=".csv,.xlsx,.xls,.pdf"
					onChange={ handleFileChange }
				/>
				<p>
					{ file
						? file.name
						: __(
								'Drop a file here, or click to choose one (XLSX, XLS, CSV or PDF).',
								'emberprice'
						  ) }
				</p>
			</div>

			{ isUploading && (
				<div
					className="embp-progress"
					role="progressbar"
					aria-valuemin="0"
					aria-valuemax="100"
					aria-valuenow={ progress }
					aria-label={ __( 'Upload progress', 'emberprice' ) }
				>
					<div
						className="embp-progress__bar"
						style={ { width: `${ progress }%` } }
					/>
					<span className="embp-progress__label">{ progress }%</span>
				</div>
			) }

			<Button
				variant="primary"
				disabled={ ! canSubmit }
				onClick={ handleSubmit }
			>
				{ isUploading
					? __( 'Uploading…', 'emberprice' )
					: __( 'Upload', 'emberprice' ) }
			</Button>
		</div>
	);
}
