import React, { useEffect, useState } from 'react'
import Layout from '../components/layout'
import AddressItem from '$theme-components/addresses/AddressItem'
import './Addresses.scss'
import Search from '../components/addresses/Search'
import { UStoreProvider } from '@ustore/core'
import { t } from '$themelocalization'

const Addresses = (props) => {
	const [searchValue, setSearchValue] = useState('')
	const [searchQuery, setSearchQuery] = useState('')
	const [addresses, setAddresses] = useState([])
	const [hideShipping, setHideShipping] = useState(true)
	const [isLoading, setIsLoading] = useState(false)

	useEffect(() => {
		if (
			UStoreProvider.state.get()['currentStore']?.Attributes?.find(
				(attr) => attr.Name === 'DeliveryEnabled' && attr.Value === 'True'
			)
		) {
			setHideShipping(false)
		}
		const fetchAddresses = async () => {
			const addresses = await UStoreProvider.api.addresses.getAddresses()
			setAddresses(addresses)
			setIsLoading(false)
		}
		setIsLoading(true)
		fetchAddresses()
	}, [])

	const handleAddressDeleted = (addressId) => {
		setAddresses((prevAddresses) =>
			prevAddresses.filter((addr) => addr.ID !== addressId)
		)
	}

	const handleAllAddressDeleted = (type) => {
		setAddresses((prevAddresses) =>
			prevAddresses.filter((addr) => addr.Type !== type)
		)
	}

	const handleSearch = (query) => {
		setSearchQuery(query.toLowerCase().trim())
	}

	const handleClose = () => {
		setSearchValue('')
		setSearchQuery('')
	}

	useEffect(() => {
		if (!searchValue || searchValue.trim() === '') {
			setSearchQuery('')
		}
	}, [searchValue])

	const handleAddressAdded = (newAddressId, newAddress) => {
		setAddresses((prevAddresses) => {
			const editedAddress = prevAddresses.find(
				(addr) => addr.ID === newAddressId
			)
			if (editedAddress) {
				return prevAddresses.map((addr) =>
					addr.ID === newAddressId
						? { ID: newAddressId, ...newAddress }
						: addr
				)
			} else {
				return [
					{ ID: newAddressId, ...newAddress },
					...prevAddresses,
				]
			}
		})
	}

	const getAddresses = async () => {
		const addresses =
			await UStoreProvider.api.addresses.getAddresses()
		setAddresses(addresses)
	}

	return (
		<Layout {...props}>
			<div className='addresses-ng'>
				<div className='addresses-page-header'>
					<h2 className='addresses-page-title'>{t('Addresses.Title')}</h2>
					<div className='addresses-page-search'>
						<Search
							placeholder={t('Addresses.Search.Placeholder')}
							value={searchValue ?? ''}
							onChange={(val) => setSearchValue(val ?? '')}
							onSearch={handleSearch}
							onClose={handleClose}
						/>
					</div>
				</div>
				<div className='addresses-page-content'>
					<div className='addresses-page-billing'>
						<AddressItem
							type={2}
							addressesList={addresses?.filter((a) => a.Type === 2)}
							search={searchQuery}
							onAddressDeleted={handleAddressDeleted}
							onAllAddressDeleted={() => handleAllAddressDeleted(2)}
							isLoading={isLoading}
							getAddress={getAddresses}
							onAddressAdded={handleAddressAdded}
						/>
					</div>
					{!hideShipping && (
						<div className='addresses-page-shipping'>
							<AddressItem
								type={1}
								addressesList={addresses?.filter((a) => a.Type === 1)}
								search={searchQuery}
								onAddressDeleted={handleAddressDeleted}
								onAllAddressDeleted={() => handleAllAddressDeleted(1)}
								isLoading={isLoading}
								getAddress={getAddresses}
								onAddressAdded={handleAddressAdded}
							/>
						</div>
					)}
				</div>
			</div>
		</Layout>
	)
}

export default Addresses
