import React, { useEffect, useState } from "react";
import { TransRoutesService } from "../../services";
import { useDispatch } from "react-redux";
import { transRoutesSlice, selectBreakfastsLoaded } from "./../../store";
import moment from 'moment';


const BreakfastSection = ({transRoutes, breakfastRecords, sectionName, confimHasBreakfast, removeBreakfastRecord}) => {
	const [customers, setCustomers] = useState([]);
	const dispatch = useDispatch();
	const { fetchAllBreakfastRecords }  = transRoutesSlice.actions;

	const createBreakfastForAll = async () => {
		for (const c of customers) {
			await TransRoutesService.createBreakfastRecords({
				customer_id: c?.customer_id,
				customer_name: c?.customer_name,
				has_breakfast: true,
				date: moment(new Date()).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()
				}]
			})
		};
		dispatch(fetchAllBreakfastRecords());
	}

	useEffect(() => {
		const routeCustomers = TransRoutesService.getAllInCenterCustomersFromRoutes(transRoutes, breakfastRecords);
		setCustomers(routeCustomers);
	}, [breakfastRecords, transRoutes]);



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

export default BreakfastSection;