import { __ } from '@wordpress/i18n';
import { useMemo } from '@wordpress/element';
import {
	Card,
	CardBody,
	CardHeader,
	Flex,
	FlexItem,
	Icon,
	Tooltip,
} from '@wordpress/components';
import { edit } from '@wordpress/icons';
import type { StoreSettingsResponse } from '../../types/settings';
import type { Order } from '../../types';

export interface AddressBlockProps {
	title: string;
	addressData: StoreSettingsResponse | Order;
	tooltip?: string;
	editUrl?: string;
	type: 'storeAddress' | 'orderAddress';
}

function toTitleCase(text: string): string {
	return text
	  .toLowerCase()
	  .replace(/(^|\s|-)\w/g, (char) => char.toUpperCase());
  }

export default function AddressBlock({
	title,
	addressData,
	editUrl,
	tooltip,
	type,
}: AddressBlockProps) {
	const addressObject = useMemo(() => {
		if (type === 'storeAddress') {
			const storeAddress = addressData as StoreSettingsResponse;
			return (
				<>
				<strong>{toTitleCase(storeAddress.contactName || storeAddress.organisation)}</strong>
				<span>{storeAddress.property}, {storeAddress.street}</span>
				<span>{storeAddress.town}, {storeAddress.county} {storeAddress.postcode}</span>
				<span>{storeAddress.countryName}</span>
				<span>{storeAddress.email}</span>
				<span>{storeAddress.phone}</span>
				</>
			)
		} else {
			const orderAddress = addressData as Order;
			return (
				<>
				<strong>{toTitleCase(orderAddress.customer?.name)}</strong>
				<span>{orderAddress.shipping?.company}</span>
				<span>{orderAddress.shipping?.address_1} {orderAddress.shipping?.address_2}</span>
				<span>{orderAddress.shipping?.city}, {orderAddress.shipping?.state}, {orderAddress.shipping?.postcode}</span>
				<span>{orderAddress.shipping?.country_name}</span>
				<span>{orderAddress.customer?.email}</span>
				<span>{orderAddress.shipping?.phone}</span>
				</>
			)
		}
	}, [addressData, type]);

	return (
		<Card size="large" style={{ flex: 1, minWidth: 0 }}>
			<CardHeader>
				<Flex justify="space-between" align="center">
					<FlexItem>
						<h3 style={{ fontSize: '1rem', fontWeight: 600, margin: 0 }}>
							{title}
						</h3>
					</FlexItem>
					{editUrl && (
						<FlexItem>
							<Tooltip text={tooltip}>
								<span style={{ display: 'inline-flex', cursor: 'pointer' }}>
									<a
										href={editUrl}
										target="_blank"
										rel="noopener noreferrer"
										style={{
											display: 'inline-flex',
											alignItems: 'center',
											color: 'inherit',
										}}
										aria-label={__('Edit address', 'parcel2go-shipping')}
									>
										<Icon icon={edit} size={24} />
									</a>
								</span>
							</Tooltip>
						</FlexItem>
					)}
				</Flex>
			</CardHeader>
			<CardBody>
				<address
					style={{
						fontStyle: 'normal',
						display: 'flex',
						flexDirection: 'column',
						gap: 4,
					}}
				>
					{addressObject}
				</address>
			</CardBody>
		</Card>
	);
}
