import { useMemo, useState } from 'react';
import { __ } from '@wordpress/i18n';
import {
	Button,
	Card,
	CardBody,
	CardHeader,
	Flex,
	FlexItem,
	TextControl,
} from '@wordpress/components';
import { chevronRight } from '@wordpress/icons';
import { formatAddressLine } from '../utils/address';
import { formatShortDate, getCourierLogo } from '../../../shared/utils';
import { Quote } from 'types/quote';
import { PluginSettings } from '../../../types';
import { Order } from '../../../types/order';
import { Dropshop } from '../../../types/dropshop';
import {
	getQuotesValidCollectionDates,
	isQuoteDropoff,
	metersToMiles,
} from '../utils/quoteHelpers';
import DropshopModal from '../dropshop-modal';

interface ServiceSectionProps {
	quote: Quote;
	store: PluginSettings['shipping'];
	order: Order;
	collectionDate: string | null;
	quoteDropshops: Dropshop[];
}

const ServiceSection = ({
	quote,
	store,
	order,
	collectionDate,
	quoteDropshops,
}: ServiceSectionProps) => {
	const [openDropshop, setOpenDropshop] = useState<boolean>(false);
	const { service } = quote ?? {};
	const logo = getCourierLogo(service?.courierSlug || service?.courier);
	const isDropoff = isQuoteDropoff(quote);
	const nearestShop = quoteDropshops?.[0];
	const hasDropshops = isDropoff && quoteDropshops?.length > 0;
	const dropoffLabel =
		isDropoff && nearestShop
			? `${__('Drop off today', 'parcel2go-shipping')}. (${metersToMiles(Number(nearestShop.distance) || 0)})`
			: __('Collection', 'parcel2go-shipping');

	const estimatedDeliveryDate = useMemo(() => {
		if (!quote) return undefined;
		const dates = getQuotesValidCollectionDates(quote);
		if (!collectionDate) return dates[0]?.delivery?.dateMin;
		const date = dates.find((d) => d.collection.date === collectionDate);
		if (!date) return dates[0]?.delivery?.dateMin;
		return date.delivery.dateMin;
	}, [collectionDate, quote]);

	return (
		<Card size="small" style={{ background: '#f6f7f7' }}>
			<CardHeader>
				<Flex gap={3} align="flex-start" justify="space-between">
					<Flex gap={2} align="flex-start" justify="flex-start">
						<FlexItem>
							<img
								src={logo}
								alt={service.name}
								style={{
									width: 48,
									height: 48,
									borderRadius: 4,
									objectFit: 'contain',
									background: '#fff',
								}}
							/>
						</FlexItem>
						<FlexItem>
							<div style={{ fontWeight: 600 }}>
								{service.courier} {service.name}
							</div>
							{hasDropshops ? (
								<>
									<Button
										variant="link"
										size="default"
										onClick={() => setOpenDropshop(true)}
										icon={chevronRight}
										iconPosition="right"
										style={{ marginLeft: 0, padding: 0 }}
									>
										{dropoffLabel}
									</Button>
									{openDropshop && (
										<DropshopModal
											dropshops={quoteDropshops}
											onRequestClose={() =>
												setOpenDropshop(false)
											}
										/>
									)}
								</>
							) : (
								<div
									style={{
										fontSize: 13,
										color: '#646970',
									}}
								>
									{dropoffLabel}
								</div>
							)}
						</FlexItem>
					</Flex>
					<FlexItem>
						<div style={{ fontSize: 13, color: '#646970' }}>
							{__('Estimated Delivery', 'parcel2go-shipping')}:{' '}
							{formatShortDate(estimatedDeliveryDate)}
						</div>
					</FlexItem>
				</Flex>
			</CardHeader>
			<CardBody>
				<Flex direction="column" gap={2}>
					<h4 style={{ margin: 0 }}>
						{__(
							'Shipping Details',
							'parcel2go-shipping'
						).toUpperCase()}
					</h4>
					<Flex gap={2} justify="space-between" align="flex-start">
						<Flex gap={3} align="flex-start" justify="flex-start">
							<FlexItem>
								<strong>
									{__('From:', 'parcel2go-shipping')}
								</strong>
							</FlexItem>
							<FlexItem>
								<div>
									<span>
										{store.property} {store.street}
									</span>
									<span>
										{store.town}, {store.county},{' '}
										{store.postcode}
									</span>
									<span>{store.countryName}</span>
								</div>
							</FlexItem>
						</Flex>
						<Flex gap={3} align="flex-start" justify="flex-start">
							<FlexItem>
								<strong>
									{__('To:', 'parcel2go-shipping')}
								</strong>
							</FlexItem>
							<FlexItem>
								<div>{formatAddressLine(order?.shipping)}</div>
							</FlexItem>
						</Flex>
					</Flex>
				</Flex>
			</CardBody>
		</Card>
	);
};

export default ServiceSection;
