import React from 'react';

const CircularTable = ({tableNumber, guests = [], inCenterCustomerIds = [], onSeatClick, labels = []}) => {
	const getPositions = () => {
		const positions = [];
		const seatCount = 8;
		const radius = 60;

		for (let i=0; i< seatCount; i++) {
			const angle = ((i*360) / seatCount - 90) * (Math.PI / 180);

			const x = radius * Math.cos(angle);
			const y = radius * Math.sin(angle);

			positions.push({x, y, angle})
			
		}
		return positions;
	}

	// Check if a customer is in-center (checked in)
	const isCustomerInCenter = (customerId) => {
		if (!customerId) return true; // Empty seats are not grayed out
		return inCenterCustomerIds.includes(customerId);
	}

	const seatPositions = getPositions();
	// const defaultNames = ['Guest 1', 'Guest 2', 'Guest 3', 'Guest 4', 'Guest 5', 'Guest 6', 'Guest 7', 'Guest 8' ];
	const defaultSeatNumber = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];

	// This is just for test purpose
	// const guestNames = [...guests];
	// while (guestNames.length < 8) (guestNames.push(defaultNames[guestNames.length]));

	return (
		<div className="circular-table-container">
			<div className="table-circle">
				<div className="table-number">{tableNumber}</div>

				{seatPositions.map((pos, index) => {
					const guest = guests[index];
					const isInCenter = isCustomerInCenter(guest?.customerId);
					const hasCustomer = guest?.customerId && guest?.customerName;
					const latestLabelColor = guest?.label?.id
						? labels.find((item) => item?.id === guest?.label?.id)?.label_color
						: undefined;
					const seatLabelColor = latestLabelColor || guest?.label?.label_color;
					
				// Determine seat style: 
				// - Apply label color if it exists
				// - Gray out if customer is assigned but not in-center (and no label color)
				const seatStyle = {
					...(seatLabelColor ? { background: seatLabelColor } : {}),
					...(!isInCenter && hasCustomer && !seatLabelColor ? { background: '#cccccc', opacity: 0.6 } : {}),
					...(!isInCenter && hasCustomer ? { opacity: 0.6 } : {})
				};
				const labelOffsetDistance = 20;
				const labelLift = 16;
				const labelOffsetX = Math.cos(pos.angle) * labelOffsetDistance;
				const labelOffsetY = Math.sin(pos.angle) * labelOffsetDistance - labelLift;
				const guestNameStyle = {
					transform: `translate(-50%, -50%) translate(${labelOffsetX}px, ${labelOffsetY}px)`,
					...(!isInCenter && hasCustomer ? { color: '#999', fontSize: '8px' } : {})
				};
					
				return (<div className="seat-container" key={index} style={{transform: `translate(${pos.x}px, ${pos.y}px)`}}>
					<div className="guest-name" style={guestNameStyle}>
						{guest?.customerName || ''}
					</div>
					<div 
						className={`seat-circle ${hasCustomer ? 'has-customer' : ''}`} 
						style={seatStyle}
						onClick={() => hasCustomer && onSeatClick && onSeatClick(guest)}
					>
						{defaultSeatNumber[index]}
					</div>
				</div>)
				})}
			</div>
		</div>
	)
}

export default CircularTable;