import { useState, useRef, useEffect } from 'react'
import AddressModal from './AddressModal'
import { RadioGroup, ButtonAria, Icon } from '$core-components'
import { UStoreProvider } from '@ustore/core'
import './AddressImport.scss'
import AddressImportWarning from './AddressImportWarning'
import { getAddressTypeLabel } from './addressUtils'
import { t } from '$themelocalization'
import { useMobile } from '$themehooks'

const AddressImport = ({
	type,
	showModal,
	setShowModal,
	onAddressAdded,
}) => {
	const [selectedFile, setSelectedFile] = useState(null)
	const [allowOverwrite, setAllowOverwrite] = useState(true)
	const [error, setError] = useState('')
	const [showModalError, setShowModalError] = useState(false)
	const [rowsWithErrors, setRowsWithErrors] = useState([])
	const fileInputRef = useRef(null)
	const addressTypeLabel = getAddressTypeLabel(type)
	const isMobile = useMobile()


	useEffect(() => {
		if (!showModal) {
			setSelectedFile(null)
			setAllowOverwrite(true)
			setError('')
			setRowsWithErrors([])
			setShowModalError(false)
			if (fileInputRef.current) {
				fileInputRef.current.value = ''
			}
		}
	}, [showModal])

	const handleFileChange = (event) => {
		const file = event.target.files[0]
		setSelectedFile(file)
		setError('')
	}

	const handleBrowseClick = () => {
		fileInputRef.current?.click()
	}

	const handleAction = () => {
		if (!selectedFile) {
			setError(t('AddressImport.Error.SelectFile'))
			return
		}
		uploadFile(selectedFile)
		setError('')
		setShowModal(false)
	}

	const handleCancel = () => {
		setShowModal(false)
	}

	const uploadFile = async (uploadedFile) => {
		try {
			const response = await UStoreProvider.api.addresses.uploadAddressFile(
				uploadedFile
			)
			const token = response?.[0].Token
			const importAddresses = await UStoreProvider.api.addresses.importAddress({
				FileToken: token,
				Type: type,
				AllowOverwrite: allowOverwrite,
			})
			if (importAddresses?.SkippedRows?.length) {
				setRowsWithErrors(importAddresses.SkippedRows)
				setShowModalError(true)
			} else {
				onAddressAdded()
			}
		} catch (error) {
			setShowModalError(true)
			return
		}
	}

	return (
		<>
			<AddressModal
				open={showModal}
				title={isMobile ? t('AddressImport.Title.Small') : t('AddressImport.Title', { type: addressTypeLabel })}
				actionButtonText={t('AddressImport.Button.Import')}
				cancelButtonText={t('AddressForm.Button.Cancel')}
				onAction={handleAction}
				onCancel={handleCancel}
			>
				<div className='address-import-modal-body'>
					<p className='address-import-description'>
						{t('AddressImport.Description')}
					</p>
					<RadioGroup
						groupName='address-import'
						className={'address-import-radio'}
						options={[
							{ value: true, label: t('AddressImport.Option.Update') },
							{ value: false, label: t('AddressImport.Option.CreateNew') },
						]}
						selectedValue={allowOverwrite}
						onChange={(value) => {
							setAllowOverwrite(value)
						}}
					/>
					<div className='address-import-file-upload'>
						<input
							ref={fileInputRef}
							type='file'
							className='address-import-file-input'
							onChange={handleFileChange}
							accept='.csv,.xlsx,.xls'
						/>
						<div className='address-import-file-controls'>
							<ButtonAria
								className='button address-import-browse-button'
								onClick={handleBrowseClick}
								noTruncate={true}
							>
								<Icon
									name='upload.svg'
									width='16px'
									height='16px'
									title={t('AddressImport.Button.Upload')}
								/>
								<span>{t('AddressImport.Button.Browse')}</span>
							</ButtonAria>
							<span className='address-import-file-name'>
								{selectedFile ? selectedFile.name : t('AddressImport.File.NoFileChosen')}
							</span>
						</div>
						{error && (
							<div className='address-import-error'>{error}</div>
						)}
					</div>
				</div>
			</AddressModal>
			<AddressImportWarning
				showModal={showModalError}
				setShowModal={setShowModalError}
				rowsWithErrors={rowsWithErrors}
			/>
		</>
	)
}

export default AddressImport
