import React, { useEffect, useState, useCallback } from "react";
import { TransRoutesService } from "../../services";
import BreakfastSection from './BreakfastSection';
import LunchSection from "./LunchSection";
import SnackSection from "./SnackSection";
import { Breadcrumb } from "react-bootstrap";
import moment from 'moment';

const MealStatus = () => {
  const [selectedDate, setSelectedDate] = useState(new Date());
  const [allRoutes, setAllRoutes] = useState([]);
  const [breakfastRecords, setBreakfastRecords] = useState([]);
  const [lunchRecords, setLunchRecords] = useState([]);
  const [snackRecords, setSnackRecords] = useState([]);

  const dateText = moment(selectedDate).format('MM/DD/YYYY');

  const fetchAllData = useCallback(() => {
    const formattedDate = moment(selectedDate).format('MM/DD/YYYY');
    TransRoutesService.getAll(formattedDate).then(res => {
      setAllRoutes(res?.data || []);
    }).catch(() => setAllRoutes([]));
    TransRoutesService.getAllBreakfastRecords(formattedDate).then(res => {
      setBreakfastRecords(res?.data || []);
    }).catch(() => setBreakfastRecords([]));
    TransRoutesService.getAllLunchRecords(formattedDate).then(res => {
      setLunchRecords(res?.data || []);
    }).catch(() => setLunchRecords([]));
    TransRoutesService.getAllSnackRecords(formattedDate).then(res => {
      setSnackRecords(res?.data || []);
    }).catch(() => setSnackRecords([]));
  }, [selectedDate]);

  useEffect(() => {
    fetchAllData();
  }, [fetchAllData]);

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

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

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

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

  const confimHasBreakfast = (customer) => {
    TransRoutesService.createBreakfastRecords({
      customer_id: customer?.customer_id,
      customer_name: customer?.customer_name,
      has_breakfast: true,
      date: dateText,
      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(() => {
      fetchAllData();
    })
  }

  const confirmHasLunch = (customer) => {
    TransRoutesService.createLunchRecords({
      customer_id: customer?.customer_id,
      customer_name: customer?.customer_name,
      has_lunch: true,
      date: dateText,
      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(() => {
      fetchAllData();
    })
  }

  const confirmHasSnack = (customer) => {
    TransRoutesService.createSnackRecords({
      customer_id: customer?.customer_id,
      customer_name: customer?.customer_name,
      has_snack: true,
      date: dateText,
      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(() => {
      fetchAllData();
    })
  }

  const removeBreakfastRecord = (customer_id) => {
    const breakfast = breakfastRecords.find(b => b.customer_id === customer_id)?.id;
    TransRoutesService.deleteBreakfastRecords(breakfast).then(() => {
      fetchAllData();
    })
  }

  const removeLunchRecord = (customer_id) => {
    const lunch = lunchRecords.find(b => b.customer_id === customer_id)?.id;
    TransRoutesService.deleteLunchRecords(lunch).then(() => {
      fetchAllData();
    })
  }

  const removeSnackRecord = (customer_id) => {
    const snack = snackRecords.find(b => b.customer_id === customer_id)?.id;
    TransRoutesService.deleteSnackRecords(snack).then(() => {
      fetchAllData();
    })
  }

  return (
    <>
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/">Lobby</Breadcrumb.Item>
          <Breadcrumb.Item active>
            Meal Status
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
          <h4>Meal Status</h4>
        </div>
        <div className="col-md-12 d-flex align-items-center" style={{ marginTop: '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">
              <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>

      <div className="app-main-content-list-container" style={{ marginTop: '16px' }}>
        <div className="list row">
          <div className="col-md-4 col-sm-12 mb-4">
            <BreakfastSection 
              transRoutes={allRoutes} 
              breakfastRecords={breakfastRecords} 
              confimHasBreakfast={confimHasBreakfast} 
              removeBreakfastRecord={removeBreakfastRecord} 
              sectionName={'Breakfast Info'}
              selectedDate={selectedDate}
              refreshRecords={fetchAllData}
            />
          </div>
          <div className="col-md-4 col-sm-12 mb-4">
            <LunchSection 
              transRoutes={allRoutes} 
              lunchRecords={lunchRecords} 
              confirmHasLunch={confirmHasLunch} 
              removeLunchRecord={removeLunchRecord} 
              sectionName={'Lunch Info'}
              selectedDate={selectedDate}
              refreshRecords={fetchAllData}
            />
          </div>
          <div className="col-md-4 col-sm-12 mb-4">
            <SnackSection 
              transRoutes={allRoutes} 
              snackRecords={snackRecords} 
              confirmHasSnack={confirmHasSnack} 
              removeSnackRecord={removeSnackRecord} 
              sectionName={'Snack Info'}
              selectedDate={selectedDate}
              refreshRecords={fetchAllData}
            />
          </div>
        </div>
      </div>
    </>
  );
};

export default MealStatus;

