import React, { useEffect, useState } from 'react';
import Avatar from '../common/Avatar';
import { convertShortTime } from '../../utils/dateUtils';
import RenderAttendanceStatus from './RenderAttendanceStatus';
import { useSelector, useDispatch } from 'react-redux';
import { fetchAttendanceData } from '../../slices/apiSlice/attedanceLogsSlice';

const AttendanceLog = ({ attendance, handleModalData, projectId }) => {
  const [attendances, setAttendnaces] = useState([]);
  const [selectedDate, setSelectedDate] = useState('');
  const dispatch = useDispatch();
  const { data, loading, error } = useSelector((store) =>  store.attendanceLogs);

  // Set the default selected date to the current date
  const currentDate = new Date().toISOString().split('T')[0]; // "YYYY-MM-DD"

  const handleDateChange = (e) => {
    const date = e.target.value;
    setSelectedDate(date);
    if (date) {
      dispatch(fetchAttendanceData({ projectId, date: date }));
    }
  };

  useEffect(() => {
    // If attendance has check-in time, filter it
    setAttendnaces(attendance?.filter((record) => record.checkInTime !== null));
    setSelectedDate(currentDate); // Set default selected date to today
  }, [attendance]);

  const renderAttendanceData = selectedDate === currentDate ? attendances : data;

  return (
    <>
      <div className="dataTables_length text-start py-2" id="DataTables_Table_0_length">
        <div className="col-md-3">
          <input
            className="form-control form-control-sm"
            type="date"
            placeholder="Select Date"
            value={selectedDate}
            onChange={handleDateChange}
            id="html5-date-input"
          />
        </div>
      </div>

      <div className="table-responsive text-nowrap">
        {attendance && attendance.length > 0 ? (
          <table className="table mb-0">
            <thead>
              <tr>
                <th className="border-top-0" colSpan={2}>Name</th>
                <th>
                  <i className="bx bxs-down-arrow-alt text-success"></i> Check-In
                </th>
                <th>
                  <i className="bx bxs-up-arrow-alt text-danger"></i> Check-Out
                </th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              {loading && <td colSpan={5}>Loading...</td>}
              {error && <td colSpan={5}>{error}</td>}
              {selectedDate && renderAttendanceData.length === 0 && (
                <td colSpan={5}>No Data Found</td>
              )}

              {renderAttendanceData?.map((attendance, index) => (
                <tr key={index}>
                  <td colSpan={2}> 
                    <div className="d-flex justify-content-start align-items-center">
                      <Avatar firstName={attendance.firstName} lastName={attendance.lastName} />
                      <div className="d-flex flex-column">
                        <a href="#" className="text-heading text-truncate">
                          <span className="fw-medium">
                            {attendance.firstName} {attendance.lastName}
                          </span>
                        </a>
                      </div>
                    </div>
                  </td>
                  <td>{convertShortTime(attendance.checkInTime)}</td>
                  <td>{attendance.checkOutTime ? convertShortTime(attendance.checkOutTime) : '--'}</td>
                  <td className="text-center">
                    <RenderAttendanceStatus
                      attendanceData={attendance}
                      handleModalData={handleModalData}
                      Tab={2}
                      currentDate={currentDate}
                    />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <span>No employee logs</span>
        )}
      </div>
    </>
  );
};

export default AttendanceLog;
