import React from 'react';
import classNames from 'classnames';
import {
	DndContext,
	closestCenter,
	KeyboardSensor,
	PointerSensor,
	useSensor,
	useSensors,
} from '@dnd-kit/core';
import type { DragEndEvent } from '@dnd-kit/core';
import {
	arrayMove,
	SortableContext,
	sortableKeyboardCoordinates,
	verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { PricingLevel } from './pricing-level';
import { useBoundStore } from '../../store/store';
import { AddNewPricingLevelButton } from './add-new-pricing-level-button';
import type { Product } from '../../typings/types';

interface ProductProps {
	product: Product;
}

export function Product(props: ProductProps) {
	const { product } = props;
	const { pricingLevels } = product;
	const { activeProductId, setActiveProductId, setPricingLevelOrder } =
		useBoundStore((state) => ({
			activeProductId: state.activeProductId,
			setActiveProductId: state.setActiveProductId,
			setPricingLevelOrder: state.setPricingLevelOrder,
		}));

	const sensors = useSensors(
		useSensor(PointerSensor, {
			activationConstraint: {
				distance: 8,
			},
		}),
		useSensor(KeyboardSensor, {
			coordinateGetter: sortableKeyboardCoordinates,
		})
	);

	const handleProductDrawerToggle = () => {
		if (activeProductId === String(product.id)) {
			setActiveProductId(null);
		} else {
			setActiveProductId(product.id);
		}
	};

	const handleDragEnd = (event: DragEndEvent) => {
		const { active, over } = event;

		if (over && active.id !== over.id) {
			const oldIndex = pricingLevels.findIndex(
				(item) => item.uuid === active.id
			);
			const newIndex = pricingLevels.findIndex(
				(item) => item.uuid === over.id
			);

			const nextOrder = arrayMove(pricingLevels, oldIndex, newIndex);
			setPricingLevelOrder(product.id, nextOrder);
		}
	};

	const productWrapperId = `gwcp-product-${product.id}`;

	return (
		<div
			id={productWrapperId}
			key={`gwcp-product-${product.id}`}
			className={classNames({
				'gwcp-product': true,
				open: activeProductId === String(product.id),
				'gform-settings-panel': true,
				'gform-settings-panel--full': true,
			})}
			data-productid={product.id}
		>
			<div
				role="button"
				className="gform-settings-panel__title gwcp-product__title gwcp-cursor-pointer gwcp-line-height-1rem gwcp-product-expander"
				tabIndex={0}
				onKeyDown={(event) => {
					if (event.key === 'Enter' || event.key === ' ') {
						handleProductDrawerToggle();
					}
				}}
				onClick={(e) => {
					e.preventDefault();
					handleProductDrawerToggle();
				}}
			>
				<h4 tabIndex={0}>{product.label}</h4>
				<div
					className={classNames({
						'gform-settings-panel__collapsible-toggle': true,
						'gwcp-product-expander-open':
							activeProductId !== String(product.id),
					})}
				></div>
			</div>

			{activeProductId === String(product.id) && (
				<div className="">
					<div
						className="gwcp-pricing-levels"
						data-productid={product.id}
					>
						<DndContext
							sensors={sensors}
							collisionDetection={closestCenter}
							onDragEnd={handleDragEnd}
						>
							<SortableContext
								items={pricingLevels.map(
									(pricingLevel) => pricingLevel.uuid
								)}
								strategy={verticalListSortingStrategy}
							>
								{pricingLevels.map((pricingLevel, i) => (
									<PricingLevel
										key={`${product.id}_pricing_level_${i}`}
										pricingLevel={pricingLevel}
									/>
								))}
							</SortableContext>
						</DndContext>
					</div>
					<AddNewPricingLevelButton productId={product.id} />
				</div>
			)}
		</div>
	);
}
