import { Quote } from 'types/quote';
import {
	getQuotesValidCollectionDates,
	isQuoteDDP,
	isQuoteDropoff,
} from '../utils/quoteHelpers';
import { useMemo } from 'react';
import {
	Card,
	CardBody,
	CheckboxControl,
	Flex,
	SelectControl,
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { formatLongDate, formatShortDate } from '../../../shared/utils';

interface OptionsSectionProps {
	quote: Quote;
	collectionDate: string | null;
	hasDDP: boolean;
	initialExtras: string[];
	selectedExtras?: string[];
	discountCode: string | null;
	setSelectedExtras?: (extras: string[]) => void;
	onChangeCollectionDate: (
		date: string | null,
		currentExtras: string[],
		currentDiscountCode: string | null
	) => void;
	onChangeDuties: (
		ddp: boolean,
		currentExtras: string[],
		currentDiscountCode: string | null
	) => void;
}

const OptionsSection = ({
	quote,
	collectionDate,
	hasDDP,
	initialExtras,
	selectedExtras = [],
	setSelectedExtras,
	discountCode,
	onChangeCollectionDate,
	onChangeDuties,
}: OptionsSectionProps) => {
	const { availableExtras } = quote ?? {};
	const isDDPCapable = useMemo(() => isQuoteDDP(quote), [quote]);
	const isDropoff = useMemo(() => isQuoteDropoff(quote), [quote]);
	const isDDP = hasDDP ?? isDDPCapable;

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

	const proofOfDelivery = useMemo(
		() =>
			(availableExtras ?? []).find((extra) => extra.key === 'signature'),
		[availableExtras]
	);
	const deliveryGuarantee = useMemo(
		() =>
			(availableExtras ?? []).find(
				(extra) => extra.key === 'deliveryguarantee'
			),
		[availableExtras]
	);

	const hasExtras = useMemo(
		() =>
			proofOfDelivery !== undefined ||
			deliveryGuarantee !== undefined ||
			isDDPCapable,
		[proofOfDelivery, deliveryGuarantee, isDDPCapable]
	);

	if (isDropoff || !hasExtras) return null;

	return (
		<Card size="small" style={{ background: '#f6f7f7' }}>
			<CardBody>
				<Flex direction="column" gap={2}>
					<h4 style={{ margin: 0 }}>
						{__(
							'Shipping Options',
							'parcel2go-shipping'
						).toUpperCase()}
					</h4>
					{!isDropoff && (
						<SelectControl
							__next40pxDefaultSize
							__nextHasNoMarginBottom
							label={__('Collection date', 'parcel2go-shipping')}
							options={getQuotesValidCollectionDates(quote).map(
								(d) => ({
									label: formatLongDate(d.collection.date),
									value: d.collection.date,
								})
							)}
							value={collectionDate ?? ''}
							onChange={(value: string | undefined) =>
								onChangeCollectionDate(
									value ?? null,
									initialExtras.concat(selectedExtras),
									discountCode || null
								)
							}
						/>
					)}
					{hasExtras && (
						<Flex direction="column" gap={2}>
							{proofOfDelivery && (
								<CheckboxControl
									label={__(
										'Proof of delivery',
										'parcel2go-shipping'
									)}
									checked={selectedExtras.includes(
										proofOfDelivery.key
									)}
									onChange={(checked) => {
										if (checked) {
											setSelectedExtras?.([
												...selectedExtras,
												proofOfDelivery.key,
											]);
										} else {
											setSelectedExtras?.(
												selectedExtras.filter(
													(e) =>
														e !==
														proofOfDelivery.key
												)
											);
										}
									}}
								/>
							)}
							{deliveryGuarantee && (
								<CheckboxControl
									label={__(
										`Delivery guaranteed by ${formatShortDate(deliveryGuaranteeDate)}`,
										'parcel2go-shipping'
									)}
									checked={selectedExtras.includes(
										deliveryGuarantee.key
									)}
									onChange={(checked) => {
										if (checked) {
											setSelectedExtras?.([
												...selectedExtras,
												deliveryGuarantee.key,
											]);
										} else {
											setSelectedExtras?.(
												selectedExtras.filter(
													(e) =>
														e !==
														deliveryGuarantee.key
												)
											);
										}
									}}
								/>
							)}
						</Flex>
					)}
					{isDDPCapable && (
						<Flex direction="column" gap={2}>
							<CheckboxControl
								label={__(
									'Send Delivery Duty Paid (DDP)',
									'parcel2go-shipping'
								)}
								checked={hasDDP}
								onChange={(checked) =>
									onChangeDuties(
										!!checked,
										initialExtras.concat(selectedExtras),
										discountCode || null
									)
								}
							/>
							<p
								style={{
									fontSize: 12,
									color: '#646970',
								}}
							>
								{__(
									' Pay the taxes and duties to ensure faster processing and no charges for the recipient',
									'parcel2go-shipping'
								)}
							</p>
						</Flex>
					)}
				</Flex>
			</CardBody>
		</Card>
	);
};

export default OptionsSection;
