import React, { useState, useEffect, useCallback } from 'react';
import CircularTable from './CircularTable';
import { Breadcrumb, Tabs, Tab, Dropdown, Modal, Button, Form } from "react-bootstrap";
import { Columns, Download, Filter, PencilSquare, ArrowBarRight, ChevronDown, ChevronRight, FileX, ArrowsFullscreen } from "react-bootstrap-icons";
import { CustomerService, LabelService, SeatingService, TransRoutesService } from '../../services';
import { PERSONAL_ROUTE_STATUS } from '../../shared/constants';
import moment from 'moment';
import Select from 'react-select';


const Seating = () => {
	// OLD ROW-BASED INITIAL VALUE - COMMENTED OUT
	// const initialValue = {
	// 	rows: [{
	// 		id: 1,
	// 		tables: 1
	// 	}],
	// 	tables: {
	// 		'table-1': {
	// 			id: 1,
	// 			tableId: 'table-1',
	// 			seats: [
	// 				{ id: '1-A', name: 'A', customerId: '', customerName: '', label: {}, rowIndex: 1 },
	// 				{ id: '1-B', name: 'B', customerId: '', customerName: '', label: {}, rowIndex: 1 },
	// 				{ id: '1-C', name: 'C', customerId: '', customerName: '', label: {}, rowIndex: 1 },
	// 				{ id: '1-D', name: 'D', customerId: '', customerName: '', label: {}, rowIndex: 1 },
	// 				{ id: '1-E', name: 'E', customerId: '', customerName: '', label: {}, rowIndex: 1 },
	// 				{ id: '1-F', name: 'F', customerId: '', customerName: '', label: {}, rowIndex: 1 },
	// 				{ id: '1-G', name: 'G', customerId: '', customerName: '', label: {}, rowIndex: 1 },
	// 				{ id: '1-H', name: 'H', customerId: '', customerName: '', label: {}, rowIndex: 1 }
	// 			],
	// 			expanded: false,
	// 			rowIndex: 1
	// 		}
	// 	}
	// };

	// NEW COLUMN-BASED INITIAL VALUE
	const initialValue = {
		columns: [{
			id: 1,
			tables: 1
		}],
		tables: {
			'table-1': {
				id: 1,
				tableId: 'table-1',
				seats: [
					{ id: '1A', name: 'A', customerId: '', customerName: '', label: {}, columnIndex: 1 },
					{ id: '1B', name: 'B', customerId: '', customerName: '', label: {}, columnIndex: 1 },
					{ id: '1C', name: 'C', customerId: '', customerName: '', label: {}, columnIndex: 1 },
					{ id: '1D', name: 'D', customerId: '', customerName: '', label: {}, columnIndex: 1 },
					{ id: '1E', name: 'E', customerId: '', customerName: '', label: {}, columnIndex: 1 },
					{ id: '1F', name: 'F', customerId: '', customerName: '', label: {}, columnIndex: 1 },
					{ id: '1G', name: 'G', customerId: '', customerName: '', label: {}, columnIndex: 1 },
					{ id: '1H', name: 'H', customerId: '', customerName: '', label: {}, columnIndex: 1 }
				],
				expanded: false,
				columnIndex: 1
			}
		}
	};
	// OLD ROW-BASED STATE - COMMENTED OUT
	// const [tableLayout, setTableLayout] = useState({
	// 	rows: [],
	// 	tables: {}
	// });

	// NEW COLUMN-BASED STATE
	const [tableLayout, setTableLayout] = useState({
		columns: [],
		tables: {}
	});

	// OLD ROW-BASED LOGIC - COMMENTED OUT
	// const [rowCount, setRowCount] = useState(1);
	// const [tableCountsPerRow, setTableCountsPerRow] = useState([1]);

	// NEW COLUMN-BASED LOGIC
	const [columnCount, setColumnCount] = useState(1);
	const [tableCountsPerColumn, setTableCountsPerColumn] = useState([1]);

	const [currentDateRecord, setCurrentDateRecord] = useState(null);

	const [editingSeat, setEditingSeat] = useState(null);

	const [showTableLayoutConfig, setShowTableLayoutConfig] = useState(false);

	const [currentLabels, setCurrentLabels] = useState([]);

	const [newLabel, setNewLabel] = useState({ label_name: undefined, label_color: undefined});

	const [customers, setCustomers] = useState([]);

	const [showLabelConfig, setShowLabelConfig] = useState(false);
	
	const [originalLabelsList, setOriginalLabelsList] = useState([]);

	const [startAddLabel, setStartAddLabel] = useState(false);
	const [deletedItems, setDeletedItems] = useState([]);
	const [editingLabelId, setEditingLabelId] = useState(null);
	const [editingLabelName, setEditingLabelName] = useState('');
	const [editingLabelColorId, setEditingLabelColorId] = useState(null);

	const [selectedCustomer, setSelectedCustomer] = useState(undefined);
	const [selectedCustomerLabel, setSelectedCustomerLabel] = useState(undefined);
	const [selectedLabelColor, setSelectedLabelColor] = useState(undefined);
	const [inCenterCustomerIds, setInCenterCustomerIds] = useState([]);
	const [isFullScreen, setIsFullScreen] = useState(false);

	// Meal confirmation state
	const [showMealModal, setShowMealModal] = useState(false);
	const [selectedSeatCustomer, setSelectedSeatCustomer] = useState(null);
	const [breakfastRecords, setBreakfastRecords] = useState([]);
	const [lunchRecords, setLunchRecords] = useState([]);
	const [snackRecords, setSnackRecords] = useState([]);

	const [selectedDate, setSelectedDate] = useState(new Date());

	const colorsList = ['#AD967A', '#BD816E', '#2B76E5', '#66CCFF', '#0A7E22', '#00C875', '#9CD326', '#FFCB00', '#FF642E', '#FD314D', '#BB3354', '#FF158A', '#9B51E0', '#BDA8F9'];

	const isToday = moment(selectedDate).isSame(moment(), 'day');

	const goToPreviousDay = () => {
		setSelectedDate(prev => {
			const d = new Date(prev);
			d.setDate(d.getDate() - 1);
			return d;
		});
	};

	const goToNextDay = () => {
		if (isToday) return;
		setSelectedDate(prev => {
			const d = new Date(prev);
			d.setDate(d.getDate() + 1);
			// Don't go beyond today
			const today = new Date();
			today.setHours(0,0,0,0);
			d.setHours(0,0,0,0);
			if (d > today) return prev;
			return d;
		});
	};

	const goToToday = () => {
		setSelectedDate(new Date());
	};

	// Fetch meal records for selected date
	const fetchMealRecords = useCallback(() => {
		const dateStr = moment(selectedDate).format('MM/DD/YYYY');
		TransRoutesService.getAllBreakfastRecords(dateStr).then(data => setBreakfastRecords(data?.data || []));
		TransRoutesService.getAllLunchRecords(dateStr).then(data => setLunchRecords(data?.data || []));
		TransRoutesService.getAllSnackRecords(dateStr).then(data => setSnackRecords(data?.data || []));
	}, [selectedDate]);

	// Fetch seating + routes data for selected date
	const fetchSeatingData = useCallback(() => {
		const dateStr = moment(selectedDate).format('MM/DD/YYYY');

		SeatingService.getAll(dateStr).then(data => {
			const result = data?.data;
			if (result?.length > 0) {
				setTableLayout(result[0]?.seating_assignment);
				setCurrentDateRecord(result[0]);
				setColumnCount(result[0]?.seating_assignment?.columns?.length || 1);
				setTableCountsPerColumn(result[0]?.seating_assignment?.columns?.map(item => item.tables) || [1]);
			} else {
				// No record for this date - fetch all records to find the most recent one on or before this date
				SeatingService.getAll().then(allData => {
					const allRecords = allData?.data || [];
					if (allRecords.length > 0) {
						const selectedTime = new Date(selectedDate);
						selectedTime.setHours(23,59,59,999);
						const sorted = allRecords
							.filter(r => {
								const parts = r?.date?.split('/');
								if (!parts || parts.length !== 3) return false;
								return new Date(parts[2], parts[0] - 1, parts[1]).getTime() <= selectedTime.getTime();
							})
							.sort((a, b) => {
								const parseDate = (d) => {
									const parts = d?.date?.split('/');
									if (!parts || parts.length !== 3) return 0;
									return new Date(parts[2], parts[0] - 1, parts[1]).getTime();
								};
								return parseDate(b) - parseDate(a);
							});
						const latest = sorted[0];
						const layout = latest?.seating_assignment;
						if (layout) {
							setTableLayout(layout);
							setColumnCount(layout?.columns?.length || 1);
							setTableCountsPerColumn(layout?.columns?.map(item => item.tables) || [1]);
							// Only auto-create a record if viewing today
							if (moment(selectedDate).isSame(moment(), 'day')) {
								SeatingService.createNewSeating({
									date: dateStr,
									seating_assignment: layout,
									create_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
									update_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
									create_date: new Date(),
									update_date: new Date()
								}).then((newData) => {
									setCurrentDateRecord(newData?.data);
								});
							} else {
								setCurrentDateRecord(null);
							}
						} else {
							setTableLayout(initialValue);
							setCurrentDateRecord(null);
							setColumnCount(1);
							setTableCountsPerColumn([1]);
						}
					} else {
						setTableLayout(initialValue);
						setCurrentDateRecord(null);
						setColumnCount(1);
						setTableCountsPerColumn([1]);
					}
				});
			}
		});

		// Fetch inbound routes for selected date
		TransRoutesService.getAll(dateStr).then(data => {
			const routes = data?.data || [];
			const inboundRoutes = routes.filter(route => route.type === 'inbound');
			const inCenterIds = [];
			inboundRoutes.forEach(route => {
				route.route_customer_list?.forEach(customer => {
					if (customer.customer_route_status === PERSONAL_ROUTE_STATUS.IN_CENTER) {
						inCenterIds.push(customer.customer_id);
					}
				});
			});
			setInCenterCustomerIds(inCenterIds);
		});
	}, [selectedDate]);

	// Initial load: customers + labels (only once)
	useEffect(() => {
		CustomerService.getAllActiveCustomers().then(data => setCustomers(data?.data));
		LabelService.getAll('active').then((data) => {setCurrentLabels(data?.data); setOriginalLabelsList(data?.data)});
	}, []);

	// Fetch date-dependent data when selectedDate changes
	useEffect(() => {
		fetchSeatingData();
		fetchMealRecords();
	}, [fetchSeatingData, fetchMealRecords])

	// OLD ROW-BASED LOGIC - COMMENTED OUT
	// useEffect(() => {
	// 	const newRows = Array.from({length: rowCount}, (_, index) => ({
	// 		id: index+1,
	// 		tables: tableCountsPerRow[index] || 0
	// 	}));
	// 	if (rowCount !== tableLayout.rows?.length) {
	// 		setTableLayout(prevLayout => ({
	// 			...prevLayout,
	// 			rows: newRows
	// 		}));
	// 		if (tableCountsPerRow.length !== rowCount) {
	// 			setTableCountsPerRow(prev => {
	// 				const newCounts = [...prev];
	// 				while(newCounts.length < newCounts) {
	// 					newCounts.push(0);
	// 				}
	// 				return newCounts.slice(0, rowCount);
	// 			})
	// 		}
	// 	}
	// }, [rowCount]);

	// NEW COLUMN-BASED LOGIC
	useEffect(() => {
		const newColumns = Array.from({length: columnCount}, (_, index) => ({
			id: index+1,
			tables: tableCountsPerColumn[index] || 0
		}));
		if (columnCount !== tableLayout.columns?.length) {
			setTableLayout(prevLayout => ({
				...prevLayout,
				columns: newColumns
			}));
			if (tableCountsPerColumn.length !== columnCount) {
				setTableCountsPerColumn(prev => {
					const newCounts = [...prev];
					while(newCounts.length < columnCount) {
						newCounts.push(0);
					}
					return newCounts.slice(0, columnCount);
				})
			}
		}
	}, [columnCount]);

	// OLD ROW-BASED LOGIC - COMMENTED OUT
	// useEffect(() => {
	// 	const newTables = {};
	// 	let tableNumber = 1;
	// 	let startUpdate = false;

	// 	if (tableCountsPerRow.length !== tableLayout.rows.length) {
	// 		startUpdate = true;
	// 	} else {
	// 		for (let i = 0; i<tableLayout?.rows.length; i++) {
	// 			if (tableLayout.rows[i].tables !== tableCountsPerRow[i]) {
	// 				startUpdate = true;
	// 				break;
	// 			}
	// 		}
	// 	}

	// 	if (startUpdate) {
	// 		tableLayout.rows.forEach((row, rowIndex) => {
	// 			const tableCount = tableCountsPerRow[rowIndex] || 0;
	// 			row.tables = tableCount;
	// 			for (let tableIndex = 0; tableIndex < tableCount; tableIndex++) {
	// 				const tableId = `table-${tableNumber}`
	// 				if (!newTables[tableId]) {
	// 					const seats = Array.from({length: 8}, (_, seatIndex) => {
	// 						const seatLetter = String.fromCharCode(65 + seatIndex);
	// 						return {
	// 							id: `${tableNumber}-${seatLetter}`,
	// 							name: seatLetter,
	// 							customerName: '',
	// 							customerId: '',
	// 							rowIndex: rowIndex + 1,
	// 							label: {label_name: undefined, label_color: undefined}
	// 						}
	// 					});
	// 					newTables[tableId] = {
	// 						id: tableNumber,
	// 						tableId: tableId,
	// 						seats,
	// 						expanded: false,
	// 						rowIndex: rowIndex + 1
	// 					}
	// 				} else {
	// 					newTables[tableId] = tableLayout.tables[tableId];
	// 				}
	// 				tableNumber++;
	// 			}
	// 		})
	// 		setTableLayout(prevLayout => ({
	// 			...prevLayout,
	// 			rows: prevLayout.rows.map((item, index) => ({...item, tables: tableCountsPerRow[index]}) ),
	// 			tables: newTables
	// 		}));
	// 	}
	// }, [tableCountsPerRow, tableLayout.rows]);

	// NEW COLUMN-BASED LOGIC
	useEffect(() => {
		const newTables = {};
		let tableNumber = 1;
		let startUpdate = false;

		if (!tableLayout.columns) return;

		if (tableCountsPerColumn.length !== tableLayout.columns.length) {
			startUpdate = true;
		} else {
			for (let i = 0; i < tableLayout?.columns?.length; i++) {
				if (tableLayout.columns[i].tables !== tableCountsPerColumn[i]) {
					startUpdate = true;
					break;
				}
			}
		}

		if (startUpdate) {
			tableLayout.columns.forEach((column, columnIndex) => {
				const tableCount = tableCountsPerColumn[columnIndex] || 0;
				column.tables = tableCount;
				for (let tableIndex = 0; tableIndex < tableCount; tableIndex++) {
					const tableId = `table-${tableNumber}`;
					if (!newTables[tableId]) {
						const seats = Array.from({length: 8}, (_, seatIndex) => {
							const seatLetter = String.fromCharCode(65 + seatIndex);
							return {
								id: `${tableNumber}${seatLetter}`,
								name: seatLetter,
								customerName: '',
								customerId: '',
								columnIndex: columnIndex + 1,
								label: {label_name: undefined, label_color: undefined}
							}
						});
						newTables[tableId] = {
							id: tableNumber,
							tableId: tableId,
							seats,
							expanded: false,
							columnIndex: columnIndex + 1
						}
					} else {
						newTables[tableId] = tableLayout.tables[tableId];
					}
					tableNumber++;
				}
			});
			setTableLayout(prevLayout => ({
				...prevLayout,
				columns: prevLayout.columns.map((item, index) => ({...item, tables: tableCountsPerColumn[index]}) ),
				tables: newTables
			}));
		}
	}, [tableCountsPerColumn, tableLayout.columns]);

	// OLD ROW-BASED LOGIC - COMMENTED OUT
	// const handleRowCountChange = (e) => {
	// 	const count = parseInt(e.target.value) || 0;
	// 	setRowCount(count);
	// }

	// const handleTableCountChange = (rowIndex, count) => {
	// 	setTableCountsPerRow(prev => {
	// 		const newCounts = [...prev];
	// 		newCounts[rowIndex] = parseInt(count) || 0;
	// 		return newCounts;
	// 	})
	// }

	// NEW COLUMN-BASED LOGIC
	const handleColumnCountChange = (e) => {
		const count = parseInt(e.target.value) || 0;
		setColumnCount(count);
	}

	const handleTableCountChange = (columnIndex, count) => {
		setTableCountsPerColumn(prev => {
			const newCounts = [...prev];
			newCounts[columnIndex] = parseInt(count) || 0;
			return newCounts;
		})
	}

	const toggleTableExpansion = (tableId) => {
		setTableLayout(prevLayout => ({
			...prevLayout,
			tables: {
				...prevLayout.tables,
				[tableId]: {
					...prevLayout.tables[tableId],
					expanded: !prevLayout.tables[tableId].expanded
				}
			}
		}));
	}

	const cleanAndClose = () => {
		setTableLayout(currentDateRecord?.seat_assignment || initialValue);
		// OLD ROW-BASED LOGIC - COMMENTED OUT
		// setRowCount(currentDateRecord?.seat_assignment?.rows?.length || 1);
		// setTableCountsPerRow(currentDateRecord?.seat_assignment?.rows?.map(item => item.tables));
		
		// NEW COLUMN-BASED LOGIC
		setColumnCount(currentDateRecord?.seat_assignment?.columns?.length || 1);
		setTableCountsPerColumn(currentDateRecord?.seat_assignment?.columns?.map(item => item.tables) || [1]);
		setShowTableLayoutConfig(false);
		setSelectedCustomer(undefined);
		setSelectedCustomerLabel(undefined);
	}

	const saveAndClose = () => {
		if (currentDateRecord) {
			SeatingService.updateSeating(currentDateRecord?.id, { seating_assignment: tableLayout, update_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name, update_date: new Date() })
		} else {
			SeatingService.createNewSeating({
				date: moment(selectedDate).format('MM/DD/YYYY'),
				seating_assignment: tableLayout,
				create_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
				update_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
				create_date: new Date(),
				update_date: new Date()
			}).then((data) => {
				const result = data?.data;
				setCurrentDateRecord(result);
			})
		}

		setShowTableLayoutConfig(false);
		setSelectedCustomer(undefined);
		setSelectedCustomerLabel(undefined);
		
	}

	const [keyword, setKeyword] = useState('');

	// OLD ROW-BASED LOGIC - COMMENTED OUT
	// const getTotalTableNumber = () => tableCountsPerRow.reduce((acc, curr) => acc + curr, 0);

	// const tablesByRow = () => tableLayout.rows.map((row, rowIndex) => {
	// 	const rowTables = Object.values(tableLayout.tables).filter(table => table.rowIndex === rowIndex + 1).sort((a,b) => a.id - b.id);
	// 	return {
	// 		rowId: row.id,
	// 		tables: rowTables
	// 	}
	// })

	// NEW COLUMN-BASED LOGIC
	const getTotalTableNumber = () => tableCountsPerColumn.reduce((acc, curr) => acc + curr, 0);

	// Get max number of tables in any column to determine the number of visual rows
	const getMaxTablesInColumn = () => Math.max(...tableCountsPerColumn, 0);

	// Organize tables by visual rows (for display) - tables at same position in each column form a row
	const tablesByVisualRow = () => {
		const maxTables = getMaxTablesInColumn();
		const visualRows = [];
		
		for (let rowIndex = 0; rowIndex < maxTables; rowIndex++) {
			const rowTables = [];
			tableLayout.columns?.forEach((column, columnIndex) => {
				// Find the table at this row position in this column
				const columnTables = Object.values(tableLayout.tables || {})
					.filter(table => table.columnIndex === columnIndex + 1)
					.sort((a, b) => a.id - b.id);
				
				if (columnTables[rowIndex]) {
					rowTables.push(columnTables[rowIndex]);
				}
			});
			if (rowTables.length > 0) {
				visualRows.push({
					rowId: rowIndex + 1,
					tables: rowTables
				});
			}
		}
		return visualRows;
	}

	// Get all customer IDs that are already assigned to seats
	const getAssignedCustomerIds = () => {
		const assignedIds = new Set();
		Object.values(tableLayout.tables || {}).forEach(table => {
			table.seats?.forEach(seat => {
				if (seat.customerId) {
					assignedIds.add(seat.customerId);
				}
			});
		});
		return assignedIds;
	};

	const startEditingSeat = (tableId, seatId) => {
		const seat = tableLayout.tables[tableId].seats.find(seat => seat.id === seatId);
		setEditingSeat({
			tableId,
			seatId,
			customerId: seat?.customerId,
			label: seat?.label,
			customerName: seat?.customerName
		});
		setSelectedCustomer({value: seat?.customerId, label: seat?.customerName});
		setSelectedCustomerLabel({value: seat?.label?.id, label: seat?.label?.label_name});
	};

	const onCustomerChange = (selectedCustomer) => {
		const nextCustomer = selectedCustomer || { value: '', label: '' };
		setEditingSeat({
			...editingSeat,
			customerId: nextCustomer.value,
			customerName: nextCustomer.label
		});
		setSelectedCustomer(nextCustomer)
	}

	const handleLabelChange = (selectedLabel) => {
		const nextLabel = selectedLabel || { value: '', label: '' };
		setEditingSeat({
			...editingSeat,
			label: {
				label_name: nextLabel.label,
				id: nextLabel.value,
				label_color: currentLabels.find(item => item.id === nextLabel.value)?.label_color
			}
		})
		setSelectedCustomerLabel(nextLabel);
	}

	const handleNewLabelNameChange = (e) => {
		setNewLabel(prevLabel => ({
			...prevLabel,
			label_name: e.target.value
		}))
	}

	const handleNewLabelColorChange = (selectedColor) => {
		setSelectedLabelColor(selectedColor);
		setNewLabel(prevLabel => ({
			...prevLabel,
			label_color: selectedColor.value
		}))
	}

	const saveSeatEdit = () =>{
		if (!editingSeat) return;

		const {tableId, seatId, customerName, customerId, label} = editingSeat;

		setTableLayout(prevLayout => {
			const updatedSeats = prevLayout.tables[tableId].seats.map(seat => seat.id === seatId ? {...seat, customerName, customerId, label} : seat);
			const finalResult = {
				...prevLayout,
				tables: {
					...prevLayout.tables,
					[tableId]: {
						...prevLayout.tables[tableId],
						seats: updatedSeats
					}
				}
			};
			SeatingService.updateSeating(currentDateRecord?.id, { seating_assignment: finalResult, update_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name, update_date: new Date()});
			if (customerId) {
				const targetCustomer = customers.find(item => item.id === customerId);
				const existingTags = Array.isArray(targetCustomer?.tags) ? targetCustomer.tags : [];
				const nextTags = label?.label_name
					? Array.from(new Set([...existingTags, label.label_name]))
					: existingTags;
				CustomerService.updateCustomer(customerId, {
					table_id: tableId,
					seating: seatId,
					tags: nextTags,
					edit_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
					edit_date: new Date()
				});
			}
			return finalResult;
		});
		
		setEditingSeat(null);
	}

	const cancelSeatEdit = () => {
		setEditingSeat(null);
	}

	const saveLabelAndClose = () => {
		if (newLabel.label_color && newLabel.label_name) {
			LabelService.createNewLabel(newLabel).then(() => {
				LabelService.getAll('active').then(data => {
					setCurrentLabels(data?.data);
					setOriginalLabelsList(data?.data);
					setShowLabelConfig(false);
					setStartAddLabel(false);
					setNewLabel({ label_color: undefined, label_name: undefined})
				});
			});
		} 
		if (deletedItems.length > 0) {
			Promise.all(deletedItems.map(item => LabelService.updateLabel(item.id, {status: 'inactive'}))).then(() => setDeletedItems([]));
		}
		
	}

	const cleanLabelAndClose = () => {
		setCurrentLabels(originalLabelsList);
		setShowLabelConfig(false);
		setStartAddLabel(false);
		setEditingLabelId(null);
		setEditingLabelName('');
		setEditingLabelColorId(null);
	}

	const onDeleteLabel = (item) => {
		setCurrentLabels(prevLabels => prevLabels.filter(lb => lb.id !== item.id))
		setDeletedItems(prevLabels => ([
			...prevLabels,
			item
		]))
	}

	const startEditingLabel = (item) => {
		setEditingLabelId(item.id);
		setEditingLabelName(item.label_name);
	}

	const saveEditingLabel = () => {
		if (!editingLabelId || !editingLabelName.trim()) return;
		LabelService.updateLabel(editingLabelId, { label_name: editingLabelName.trim() }).then(() => {
			LabelService.getAll('active').then(data => {
				setCurrentLabels(data?.data);
				setOriginalLabelsList(data?.data);
			});
		});
		setEditingLabelId(null);
		setEditingLabelName('');
	}

	const cancelEditingLabel = () => {
		setEditingLabelId(null);
		setEditingLabelName('');
	}

	const saveEditingLabelColor = (labelId, newColor) => {
		LabelService.updateLabel(labelId, { label_color: newColor }).then(() => {
			LabelService.getAll('active').then(data => {
				setCurrentLabels(data?.data);
				setOriginalLabelsList(data?.data);
			});
		});
		setEditingLabelColorId(null);
	}

	const handleFullScreen = () => {
		setIsFullScreen(true);
	}

	const handleExitFullScreen = () => {
		setIsFullScreen(false);
	}

	// Meal confirmation functions
	const handleSeatClick = (guest) => {
		if (guest?.customerId && guest?.customerName) {
			setSelectedSeatCustomer(guest);
			setShowMealModal(true);
		}
	};

	const closeMealModal = () => {
		setShowMealModal(false);
		setSelectedSeatCustomer(null);
	};

	const hasBreakfast = (customerId) => {
		return breakfastRecords.some(record => 
			record.customer_id === customerId && 
			record.date === moment(selectedDate).format('MM/DD/YYYY')
		);
	};

	const hasLunch = (customerId) => {
		return lunchRecords.some(record => 
			record.customer_id === customerId && 
			record.date === moment(selectedDate).format('MM/DD/YYYY')
		);
	};

	const hasSnack = (customerId) => {
		return snackRecords.some(record => 
			record.customer_id === customerId && 
			record.date === moment(selectedDate).format('MM/DD/YYYY')
		);
	};

	const confirmBreakfast = (customer) => {
		TransRoutesService.createBreakfastRecords({
			customer_id: customer?.customerId,
			customer_name: customer?.customerName,
			has_breakfast: true,
			date: moment(selectedDate).format('MM/DD/YYYY'),
			create_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
			create_date: new Date(),
			edit_history: [{
				employee: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
				date: new Date()
			}]
		}).then(() => {
			fetchMealRecords();
		});
	};

	const confirmLunch = (customer) => {
		TransRoutesService.createLunchRecords({
			customer_id: customer?.customerId,
			customer_name: customer?.customerName,
			has_lunch: true,
			date: moment(selectedDate).format('MM/DD/YYYY'),
			create_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
			create_date: new Date(),
			edit_history: [{
				employee: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
				date: new Date()
			}]
		}).then(() => {
			fetchMealRecords();
		});
	};

	const confirmSnack = (customer) => {
		TransRoutesService.createSnackRecords({
			customer_id: customer?.customerId,
			customer_name: customer?.customerName,
			has_snack: true,
			date: moment(selectedDate).format('MM/DD/YYYY'),
			create_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
			create_date: new Date(),
			edit_history: [{
				employee: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
				date: new Date()
			}]
		}).then(() => {
			fetchMealRecords();
		});
	};

	const removeBreakfast = (customerId) => {
		const record = breakfastRecords.find(b => 
			b.customer_id === customerId && 
			b.date === moment(selectedDate).format('MM/DD/YYYY')
		);
		if (record) {
			TransRoutesService.deleteBreakfastRecords(record.id).then(() => {
				fetchMealRecords();
			});
		}
	};

	const removeLunch = (customerId) => {
		const record = lunchRecords.find(b => 
			b.customer_id === customerId && 
			b.date === moment(selectedDate).format('MM/DD/YYYY')
		);
		if (record) {
			TransRoutesService.deleteLunchRecords(record.id).then(() => {
				fetchMealRecords();
			});
		}
	};

	const removeSnack = (customerId) => {
		const record = snackRecords.find(b => 
			b.customer_id === customerId && 
			b.date === moment(selectedDate).format('MM/DD/YYYY')
		);
		if (record) {
			TransRoutesService.deleteSnackRecords(record.id).then(() => {
				fetchMealRecords();
			});
		}
	};

	const handleBreakfastChange = (e) => {
		if (e.target.checked) {
			confirmBreakfast(selectedSeatCustomer);
		} else {
			removeBreakfast(selectedSeatCustomer?.customerId);
		}
	};

	const handleLunchChange = (e) => {
		if (e.target.checked) {
			confirmLunch(selectedSeatCustomer);
		} else {
			removeLunch(selectedSeatCustomer?.customerId);
		}
	};

	const handleSnackChange = (e) => {
		if (e.target.checked) {
			confirmSnack(selectedSeatCustomer);
		} else {
			removeSnack(selectedSeatCustomer?.customerId);
		}
	};

	// Handle ESC key to exit full screen
	useEffect(() => {
		const handleKeyPress = (event) => {
			if (event.key === 'Escape' && isFullScreen) {
				handleExitFullScreen();
			}
		};

		if (isFullScreen) {
			document.addEventListener('keydown', handleKeyPress);
		}

		return () => {
			document.removeEventListener('keydown', handleKeyPress);
		};
	}, [isFullScreen]);

	return (
		<>
			{/* Full Screen Mode */}
			{isFullScreen && (
				<div className="app-main-content-list-container fullscreen-mode" style={{ backgroundColor: '#fff' }}>
					<div className="seating-chart-container">
						<div className="seating-stage">
							<div className="stage">Stage</div>
						</div>
						{
							tablesByVisualRow().map((rowItem, rowIndex) => {
								return (<div className="seating-row-container" id={`seating-row-fullscreen-${rowIndex}`} key={`seating-row-fullscreen-${rowIndex}`}>
									{
										rowItem?.tables?.map((item, itemIndex) => <CircularTable className="me-4" key={`seating-table-fullscreen-${rowIndex}-${itemIndex}`} id={`seating-table-fullscreen-${rowIndex}-${itemIndex}`} tableNumber={item?.id} guests={item?.seats} inCenterCustomerIds={inCenterCustomerIds} onSeatClick={handleSeatClick} labels={currentLabels} />)
									}
								</div>)
							})
						}
						<div className="seating-stage mt-4">
							{
								currentLabels.map((item) => <div key={item.id}><span style={{width: '16px', height: '16px', borderRadius: '16px', display: 'inline-block', background: item.label_color, marginRight: '8px' }}></span>{item.label_name}</div>)
							}
						</div>
					</div>
					<div className="fullscreen-hint">
						Press ESC to exit full screen
					</div>
				</div>
			)}

			{/* Normal Mode - Original Layout */}
			{!isFullScreen && (
				<div className="seating-page-container">
					<div className="list row mb-4">
						<Breadcrumb>
							<Breadcrumb.Item href="/">Lobby</Breadcrumb.Item>
							<Breadcrumb.Item active>
								Seating Chart
							</Breadcrumb.Item>
						</Breadcrumb>
						<div className="col-md-12 text-primary">
							<h4>Seating Chart</h4>
						</div>
						<div className="col-md-12 d-flex align-items-center" style={{ marginTop: '8px', marginBottom: '8px' }}>
							<div className="d-flex align-items-center" style={{ gap: '12px' }}>
								<button className="btn btn-outline-secondary btn-sm" onClick={goToPreviousDay} title="Previous day">
									<span style={{ fontSize: '18px', lineHeight: 1 }}>&lsaquo;</span>
								</button>
								<span style={{ fontWeight: 600, fontSize: '16px', minWidth: '160px', textAlign: 'center' }}>
									{moment(selectedDate).format('ddd, MMM D, YYYY')}
								</span>
								<button className="btn btn-outline-secondary btn-sm" onClick={goToNextDay} title="Next day" disabled={isToday}>
									<span style={{ fontSize: '18px', lineHeight: 1 }}>&rsaquo;</span>
								</button>
								{!isToday && (
									<button className="btn btn-outline-primary btn-sm" onClick={goToToday}>
										Today
									</button>
								)}
							</div>
						</div>
						<div className="app-main-content-list-container">
							<div className="app-main-content-list-func-container">
								<Tabs defaultActiveKey="seatingChart" id="seatingTabs">
									<Tab eventKey="seatingChart" title="Seating Chart">
										<div className="seating-chart-container">
											<div className="seating-stage">
												<div className="stage">Stage</div>
											</div>
											{
												tablesByVisualRow().map((rowItem, rowIndex) => {
													return (<div className="seating-row-container" id={`seating-row-${rowIndex}`} key={`seating-row-${rowIndex}`}>
														{
															rowItem?.tables?.map((item, itemIndex) => <CircularTable className="me-4" key={`seating-table-${rowIndex}-${itemIndex}`} id={`seating-table-${rowIndex}-${itemIndex}`} tableNumber={item?.id} guests={item?.seats} inCenterCustomerIds={inCenterCustomerIds} onSeatClick={handleSeatClick} labels={currentLabels} />)
														}
													</div>)
												})
											}
											<div className="seating-stage mt-4">
												{
													currentLabels.map((item) => <div key={item.id}><span style={{width: '16px', height: '16px', borderRadius: '16px', display: 'inline-block', background: item.label_color, marginRight: '8px' }}></span>{item.label_name}</div>)
												}
											</div>
										</div>
									</Tab>
								</Tabs>
								<div className="list-func-panel">
									<button className="btn btn-primary me-2" onClick={handleFullScreen}>
										<ArrowsFullscreen size={16} className="me-2"></ArrowsFullscreen>Full Screen
									</button>
								</div>
							</div>
						</div>
					</div>
					<div className="manage-seating-chart-container">
				<div className="manage-seating-chart-title-container">
					<h6>Manage Seating Chart</h6>
					{/* <ArrowBarRight color="#777" size={20}></ArrowBarRight> */}
				</div>
				<div className="manage-seating-chart-tables-container">
					<div className="title">
						<strong>Table Layout</strong>
						<PencilSquare color="#777" size={16} onClick={() => { setShowLabelConfig(false); setShowTableLayoutConfig(true); }}/>
						{
							showTableLayoutConfig && <div className="seating-popover">
								<h6>Manage Table Layout</h6>
								{/* OLD ROW-BASED LOGIC - COMMENTED OUT */}
								{/* <div className="app-main-content-fields-section margin-sm  dropdown-container">
									<div className="me-4">
										<div className="field-label">Number of Rows</div>
										<input type="number" min="0" value={rowCount} onChange={handleRowCountChange}></input>
									</div>
								</div>
								{
									rowCount>0 && Array.from({length: rowCount}).map((_, rowIndex) => (
										<div className="app-main-content-fields-section margin-sm  dropdown-container">
											<div className="me-4">
												<div className="field-label">{`Row ${rowIndex + 1}`}</div>
												<input type="number" min="0" value={tableCountsPerRow[rowIndex] || 0} onChange={(e) => handleTableCountChange(rowIndex, e.target.value)}/>
											</div>
										</div>
									))
								} */}

								{/* NEW COLUMN-BASED LOGIC */}
								<div className="app-main-content-fields-section margin-sm  dropdown-container">
									<div className="me-4">
										<div className="field-label">Number of Columns</div>
										<input type="number" min="0" value={columnCount} onChange={handleColumnCountChange}></input>
									</div>
								</div>
								{
									columnCount > 0 && Array.from({length: columnCount}).map((_, columnIndex) => (
										<div className="app-main-content-fields-section margin-sm  dropdown-container" key={`column-config-${columnIndex}`}>
											<div className="me-4">
												<div className="field-label">{`Column ${columnIndex + 1} (Tables)`}</div>
												<input type="number" min="0" value={tableCountsPerColumn[columnIndex] || 0} onChange={(e) => handleTableCountChange(columnIndex, e.target.value)}/>
											</div>
										</div>
									))
								}
								
								<div className="list row">
									<div className="col-md-12">
										<button className="btn btn-default btn-sm float-right" onClick={() => cleanAndClose()}> Cancel </button>
										<button className="btn btn-primary btn-sm float-right" onClick={() => saveAndClose()}> Save </button>
									</div>
								</div>
							</div>
						}
					</div>
					{
						Object.keys(tableLayout.tables).map((tableId) => (
							<div className="table-config-container">
								<div className="table-config-item-title">
									{!tableLayout.tables[tableId]?.expanded && <ChevronDown className="me-2" color="#777" size={12} onClick={() => toggleTableExpansion(tableId)} />}
									{tableLayout.tables[tableId]?.expanded && <ChevronRight className="me-2" color="#777" size={12} onClick={() => toggleTableExpansion(tableId)} />}
									{tableId.replace('-', ' ')}
								</div>
								{tableLayout.tables[tableId]?.expanded && tableLayout.tables[tableId]?.seats.map(seat => <div className="table-config-item">
									{`${seat.name}. ${seat.customerName}`} <PencilSquare color="#777" size={16} onClick={() => startEditingSeat(tableId, seat.id)} />
									{
										editingSeat && editingSeat.tableId === tableId && editingSeat.seatId === seat.id && <div className="seating-popover">
											<h6>Seat Assignment</h6>
											<div className="app-main-content-fields-section margin-sm  dropdown-container">
												<div className="me-4">
													<div className="field-label">Customer Name</div>
													<Select styles={{
														control: (baseStyles) => ({
															...baseStyles,
															width: '210px',
															borderRadius: '8px'
														}),
														indicatorSeparator: () => ({
															display: 'none'
														}),
														dropdownIndicator: (baseStyles) => ({
															...baseStyles,
															paddingRight: '8px',
															color: '#333',
															'&:hover': { color: '#000' }
														}),
														valueContainer: (baseStyles) => ({
															...baseStyles,
															height: '43px',
															padding: '0 8px',
														}),
														input: (baseStyles) => ({
															...baseStyles,
															margin: '0px',
															padding: '0px',
															height: '30px',
															width: '150px'
														}),
														placeholder: (baseStyles) => ({
															...baseStyles,
															fontSize: '13px'
														}),
														singleValue: (baseStyles) => ({
															...baseStyles,
															margin: '0px',
															fontSize: '13px'
														})
													}} value={selectedCustomer} onChange={newSelectedCustomer => onCustomerChange(newSelectedCustomer)} options={[{value: '', label: ''}, ...customers.filter(customer => {
														const assignedIds = getAssignedCustomerIds();
														// Allow active, non-discharged customers who are either:
														// 1. Not already assigned to any seat, OR
														// 2. The current customer being edited (so they can stay in their seat)
														return customer?.status === 'active' && 
															customer?.type !== 'discharged' && 
															(!assignedIds.has(customer?.id) || customer?.id === editingSeat?.customerId);
													}).map(customer => ({
														value: customer?.id || '',
														label: customer?.name || ''
													}))]}></Select>
												</div>
											</div>
											<div className="app-main-content-fields-section margin-sm  dropdown-container">
												<div className="me-4">
													<div className="field-label">Customer Label</div>
													<Select styles={{
														control: (baseStyles) => ({
															...baseStyles,
															width: '210px',
															borderRadius: '8px'
														}),
														indicatorSeparator: () => ({
															display: 'none'
														}),
														dropdownIndicator: (baseStyles) => ({
															...baseStyles,
															paddingRight: '8px',
															color: '#333',
															'&:hover': { color: '#000' }
														}),
														valueContainer: (baseStyles) => ({
															...baseStyles,
															height: '43px',
															padding: '0 8px',
														}),
														input: (baseStyles) => ({
															...baseStyles,
															margin: '0px',
															padding: '0px',
															height: '30px',
															width: '150px'
														}),
														placeholder: (baseStyles) => ({
															...baseStyles,
															fontSize: '13px'
														}),
														singleValue: (baseStyles) => ({
															...baseStyles,
															margin: '0px',
															fontSize: '13px'
														})
													}} value={ selectedCustomerLabel} onChange={selectedLabel => handleLabelChange(selectedLabel)} options={[{value: '', label: ''}, ...currentLabels.map(label => ({
														value: label?.id|| '',
														label: label?.label_name || ''
													}))]}></Select>
												</div>
											</div>
											
											<div className="list row">
												<div className="col-md-12">
													<button className="btn btn-default btn-sm float-right" onClick={() => cancelSeatEdit()}> Cancel </button>
													<button className="btn btn-primary btn-sm float-right" onClick={() => saveSeatEdit()}> Save </button>
												</div>
											</div>
										</div>
									}
								</div>)}
							</div>
						))
					}
					<div className="title">
						<strong>Customer Label</strong>
						<PencilSquare color="#777" size={16} onClick={() => { setShowTableLayoutConfig(false); setShowLabelConfig(true); }}/>
						{
							showLabelConfig && <div className="seating-popover">
								<h6>Customer Labels</h6>
								<div className="mb-4">
									{
										currentLabels.map((item) => <div className="label-delete-item" key={item.id}>
											<span 
												style={{width: '16px', height: '16px', borderRadius: '16px', background: item.label_color, flexShrink: 0, cursor: 'pointer', border: editingLabelColorId === item.id ? '2px solid #333' : 'none' }}
												onClick={() => setEditingLabelColorId(editingLabelColorId === item.id ? null : item.id)}
												title="Click to change color"
											></span>
											{editingLabelId === item.id ? (
												<div style={{ display: 'flex', alignItems: 'center', gap: '4px', flex: 1, marginLeft: '8px' }}>
													<input
														type="text"
														value={editingLabelName}
														onChange={(e) => setEditingLabelName(e.target.value)}
														onKeyDown={(e) => { if (e.key === 'Enter') saveEditingLabel(); if (e.key === 'Escape') cancelEditingLabel(); }}
														style={{ flex: 1, fontSize: '13px', padding: '2px 6px', border: '1px solid #aaa', borderRadius: '4px' }}
														autoFocus
													/>
													<button className="btn btn-primary btn-sm" style={{ padding: '1px 8px', fontSize: '12px' }} onClick={saveEditingLabel}>OK</button>
													<button className="btn btn-default btn-sm" style={{ padding: '1px 8px', fontSize: '12px' }} onClick={cancelEditingLabel}>X</button>
												</div>
											) : (
												<>
													<span style={{ flex: 1, marginLeft: '8px' }}>{item.label_name}</span>
													<PencilSquare size={14} color="#777" style={{ cursor: 'pointer', marginRight: '8px' }} onClick={() => startEditingLabel(item)} />
													<FileX size={16} style={{ cursor: 'pointer' }} onClick={() => onDeleteLabel(item)} />
												</>
											)}
											{editingLabelColorId === item.id && (
												<div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px', marginTop: '6px', padding: '6px', background: '#f8f8f8', borderRadius: '6px', width: '100%' }}>
													{colorsList.map(color => (
														<span
															key={color}
															onClick={() => saveEditingLabelColor(item.id, color)}
															style={{
																width: '20px', height: '20px', borderRadius: '50%', background: color, cursor: 'pointer',
																border: item.label_color === color ? '2px solid #333' : '2px solid transparent',
																display: 'inline-block'
															}}
														></span>
													))}
												</div>
											)}
										</div>)
									}
								</div>
								{!startAddLabel && <button className="btn btn-tertiary btn-custom-label btn-sm mb-4" onClick={() => setStartAddLabel(true)}>+ Add New Label</button>}
								{startAddLabel && <>
									<div className="app-main-content-fields-section margin-sm  dropdown-container">
										<div className="me-4">
											<div className="field-label">Label Name</div>
											<input type="text" value={newLabel.label_name} onChange={handleNewLabelNameChange}></input>
										</div>
									</div>
									<div className="app-main-content-fields-section margin-sm  dropdown-container">
										<div className="me-4">
											<div className="field-label">Label Color</div>
											{/* <select value={newLabel.label_color} onChange={handleNewLabelColorChange}>
												<option value=""></option>
												{
													colorsList.map((item) => <option style={{backgroundColor: item}} value={item}><div style={{backgroundColor: item, width: '4px', height: '4px'}}></div>{item}</option>)
												}
											</select> */}
											<Select styles={{
												control: (baseStyles) => ({
													...baseStyles,
													width: '210px',
													borderRadius: '8px'
												}),
												indicatorSeparator: () => ({
													display: 'none'
												}),
												dropdownIndicator: (baseStyles) => ({
													...baseStyles,
													paddingRight: '8px',
													color: '#333',
													'&:hover': { color: '#000' }
												}),
												valueContainer: (baseStyles) => ({
													...baseStyles,
													height: '43px',
													padding: '0 8px',
												}),
												input: (baseStyles) => ({
													...baseStyles,
													margin: '0px',
													padding: '0px',
													height: '30px',
													width: '150px'
												}),
												placeholder: (baseStyles) => ({
													...baseStyles,
													fontSize: '13px'
												}),
												singleValue: (baseStyles) => ({
													...baseStyles,
													margin: '0px',
													fontSize: '13px'
												}),
												option: (baseStyles, {data}) => ({
													...baseStyles,
													backgroundColor: data?.value
												})
											}} value={selectedLabelColor} onChange={selectedColor => handleNewLabelColorChange(selectedColor)} options={[{value: '', label: ''}, ...colorsList.map(color => ({
												value: color|| '',
												label: color || ''
											}))]}></Select>
										</div>
									</div>
								</>}
								
								<div className="list row">
									<div className="col-md-12">
										<button className="btn btn-default btn-sm float-right" onClick={() => cleanLabelAndClose()}> Cancel </button>
										<button className="btn btn-primary btn-sm float-right" onClick={() => saveLabelAndClose()}> Save </button>
									</div>
								</div>
							</div>
						}
					</div>
					{
					currentLabels.map((item) => <div className="mb-4" style={{fontSize: '12px', display: 'inline-flex', alignItems: 'center', marginRight: '16px'}} key={item.id}><span style={{width: '16px', height: '16px', borderRadius: '16px', background: item.label_color, display: 'inline-block', marginRight: '8px' }}></span>{item.label_name}</div>)
				}
				</div>
					</div>
				</div>
			)}

			{/* Meal Confirmation Modal */}
			<Modal show={showMealModal} onHide={closeMealModal} centered>
				<Modal.Header closeButton>
					<Modal.Title>Confirm Meals</Modal.Title>
				</Modal.Header>
				<Modal.Body>
					{selectedSeatCustomer && (
						<>
							<p className="mb-3">
								<strong>Customer:</strong> {selectedSeatCustomer.customerName}
							</p>
							<p className="text-muted mb-3">Please confirm the meals for today:</p>
							<Form>
								<Form.Check 
									type="checkbox"
									id="breakfast-check"
									label="Breakfast"
									checked={hasBreakfast(selectedSeatCustomer?.customerId)}
									onChange={handleBreakfastChange}
									className="mb-2"
								/>
								<Form.Check 
									type="checkbox"
									id="lunch-check"
									label="Lunch"
									checked={hasLunch(selectedSeatCustomer?.customerId)}
									onChange={handleLunchChange}
									className="mb-2"
								/>
								<Form.Check 
									type="checkbox"
									id="snack-check"
									label="Snack"
									checked={hasSnack(selectedSeatCustomer?.customerId)}
									onChange={handleSnackChange}
									className="mb-2"
								/>
							</Form>
						</>
					)}
				</Modal.Body>
				<Modal.Footer>
					<Button variant="secondary" onClick={closeMealModal}>
						Close
					</Button>
				</Modal.Footer>
			</Modal>
		</>
	)
}

export default Seating;