import { useEffect, useState } from 'react'
import AddressModal from './AddressModal'
import { Icon } from '$core-components'
import './AddressDeleteWarning.scss'
import Checkbox from './Checkbox'
import { UStoreProvider } from '@ustore/core'
import { getAddressTypeLabel } from './addressUtils'
import { t } from '$themelocalization'

const AddressDeleteWarning = ({
	showModal,
	setShowModal,
	type,
	onAddressDeleted,
}) => {
	const [isChecked, setIsChecked] = useState(false)

	useEffect(() => {
		if (!showModal) {
			setIsChecked(false)
		}
	}, [showModal])

	const handleAddressDeleted = async () => {
		try {
			await UStoreProvider.api.addresses.clearAddress({
				Type: type,
				IDs: null,
			})

			if (onAddressDeleted) {
				onAddressDeleted()
			}

			setShowModal(false)
		} catch (error) {
			console.error('Error deleting address:', error)
		}
	}

	const title = getAddressTypeLabel(type)

	return (
		<AddressModal
			open={showModal}
			title={t('AddressDeleteWarning.Title', { type: title?.toLowerCase() })}
			actionButtonText={t('AddressDeleteWarning.Button.DeleteAll')}
			cancelButtonText={t('AddressForm.Button.Cancel')}
			isActionDisabled={!isChecked}
			onAction={() => {
				handleAddressDeleted()
			}}
			onCancel={() => {
				setShowModal(false)
				setIsChecked(false)
			}}
		>
			<div className='address-delete-modal-body'>
				<div className='address-delete-modal-icon'>
					<Icon name='error.svg' width='30px' height='30px' />
				</div>
				<p className='address-delete-modal-content'>
					{t('AddressDeleteWarning.Warning.Prefix')}{' '}
					<strong>{t('AddressDeleteWarning.Warning.Highlight')}</strong>{' '}
					{t('AddressDeleteWarning.Warning.Suffix')}
				</p>
				<div className='address-delete-confirmation'>
					<Checkbox
						checked={isChecked}
						onChange={(e) => setIsChecked(e.target.checked)}
						className='address-delete-checkbox'
					>
						{t('AddressDeleteWarning.Checkbox.Confirm')}
					</Checkbox>
				</div>
			</div>
		</AddressModal>
	)
}

export default AddressDeleteWarning
