import React, { useEffect, useState } from "react";
import { TransRoutesService } from "../../services";
import moment from 'moment';


const SnackSection = ({transRoutes, snackRecords, sectionName, confirmHasSnack, removeSnackRecord, selectedDate, refreshRecords}) => {
	const [customers, setCustomers] = useState([]);

	const createSnackForAll = async () => {
		const dateStr = moment(selectedDate || new Date()).format('MM/DD/YYYY');
		const unconfirmed = customers.filter(c => !c.has_snack);
		for (const c of unconfirmed) {
			await TransRoutesService.createSnackRecords({
				customer_id: c?.customer_id,
				customer_name: c?.customer_name,
				has_snack: true,
				date: dateStr,
				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()
				}]
			})
		};
		if (refreshRecords) refreshRecords();
	}

	useEffect(() => {
		if (transRoutes && transRoutes.length > 0) {
			const routeCustomers = TransRoutesService.getAllInCenterCustomersFromRoutesForSnack(transRoutes, snackRecords || []);
			setCustomers(routeCustomers);
		}
	}, [snackRecords, transRoutes]);



	
  
  return (
    <>
      <div className="text-primary mb-4"><h5>{sectionName} {` (${customers?.length})`}</h5></div>
	  {customers?.some(c => !c.has_snack) && (<div className="mb-2 mt-2"><button onClick={() => createSnackForAll()} className="btn btn-primary btn-sm">Confirm All Snack</button></div>)}
      <div className="list row">
        <div className="col-md-12">
					<table className="personnel-info-table">
            <thead>
              <tr>
								<th>Name</th>
								<th>Has Snack Today</th>
								<th>Change Snack Status</th>
							</tr>
						</thead>
					<tbody>
						{
							customers?.map((customer) => (
								<tr key={customer?.customer_id} className={customer?.has_snack ? 'light-green' : 'red'}>
									<td>{customer?.customer_name}</td>
									<td>{customer?.has_snack ? 'Yes': 'No'}</td>
									<td>
										{!customer?.has_snack && <button className="btn btn-link btn-sm" onClick={() => confirmHasSnack(customer)}>Confirm Customer Has snack</button>}
										{customer?.has_snack && <button className="btn btn-link btn-sm" onClick={() => removeSnackRecord(customer?.customer_id)}>Mark Customer NOT have snack</button>}
									</td>
								</tr>
							))
						}
					</tbody>
					</table>
        </div>
      </div>
    </>
    
  );
};

export default SnackSection;