import React, { useEffect, useState } from "react";
import { useEmployeeAttendacesLog } from "../../hooks/useAttendance";
import { convertShortTime } from "../../utils/dateUtils";
import { useNavigate } from "react-router-dom";
import { THRESH_HOLD } from "../../utils/constants";

const AttendLogs = ({ Id }) => {
  const { logs, loading } = useEmployeeAttendacesLog(Id);
  const navigate = useNavigate();

  const isCheckoutRegularized = (
    activityTimeStr,
    checkoutTimeStr,
    threshHours
  ) => {
    if (!activityTimeStr || !checkoutTimeStr) return false;

    const activityTime = new Date(activityTimeStr);
    const checkoutTime = new Date(checkoutTimeStr);
    const threshTimeMs = threshHours * 60 * 60 * 1000;

    return checkoutTime - activityTime > threshTimeMs;
  };

  const whichActivityPerform = (actvity, checkOutTime) => {
    switch (actvity) {
      case 1:
        return (
          <i
            className="bx bx-right-arrow-circle text-success"
            data-bs-toggle="tooltip"
            data-bs-offset="0,8"
            data-bs-placement="top"
            data-bs-custom-class="tooltip"
            title="Check-In"
          ></i>
        );
        break;
      case 2:
        return (
          <i
            className="bx bx-help-circle text-danger"
            data-bs-toggle="tooltip"
            data-bs-offset="0,8"
            data-bs-placement="top"
            data-bs-custom-class="tooltip"
            title="Regularize Requested"
          ></i>
        );
        break;
      case 3:
        return (
          <i
            className="bx bx-check-circle text-success"
            data-bs-toggle="tooltip"
            data-bs-offset="0,8"
            data-bs-placement="top"
            data-bs-custom-class="tooltip"
            title="Request Deleted!"
          ></i>
        );
        break;
      case 4:
        if (
          checkOutTime &&
          isCheckoutRegularized(
            logs[0]?.activityTime,
            checkOutTime,
            THRESH_HOLD
          )
        ) {
          return (
            <i
              className="bx bx-check-circle text-success"
              data-bs-toggle="tooltip"
              data-bs-offset="0,8"
              data-bs-placement="top"
              data-bs-custom-class="tooltip"
              title="Regularized"
            ></i>
          );
        } else {
          return (
            <i
              className="bx bx-left-arrow-circle text-danger"
              data-bs-toggle="tooltip"
              data-bs-offset="0,8"
              data-bs-placement="top"
              data-bs-custom-class="tooltip"
              title="Check-Out"
            ></i>
          );
        }

        break;
      case 5:
        return (
          <i
            className="bx bx-x-circle text-danger"
            data-bs-toggle="tooltip"
            data-bs-offset="0,8"
            data-bs-placement="top"
            data-bs-custom-class="tooltip"
            title="Request Rejected"
          ></i>
        );
        break;

      default:
        break;
    }
  };
  const LocationLink = (lat, lng) => {
    const url = `https://www.google.com/maps?q=${lat},${lng}`;
    window.open(url, "_blank"); // Open in new tab
  };

  useEffect(() => {
    const tooltipTriggerList = Array.from(
      document.querySelectorAll('[data-bs-toggle="tooltip"]')
    );
    tooltipTriggerList.forEach((el) => new bootstrap.Tooltip(el));
  }, []);
  return (
    <div className="table-responsive">
      <div className="text-start">
        {logs && !loading && (
          <p>
            Attendance logs for{" "}
            {logs[0]?.employee?.firstName + " " + logs[0]?.employee?.lastName}{" "}
            on {logs[0]?.activityTime.slice(0, 10)}{" "}
          </p>
        )}
      </div>
      {loading && <p>Loading..</p>}
      {logs && logs.length > 0 && (
        <>
          <div className="d-flex justify-content-start align-items-center gap-2 my-1">
            <div className="align-item-center"></div>
          </div>

          <table className="table table-sm mb-0">
            <thead>
              <tr>
                <th>Date</th>
                <th>Time</th>
                <th>Activity</th>
                <th>Location</th>
                <th>Recored By</th>
                <th>Description</th>
              </tr>
            </thead>
            <tbody>
              {logs
                .slice()
                .sort((a, b) => b.id - a.id)
                .map((log, index) => (
                  <tr key={index}>
                    <td>{log.activityTime.slice(0, 10)}</td>
                    <td>{convertShortTime(log.activityTime)}</td>
                    <td>
                      {whichActivityPerform(log.activity, log.activityTime)}
                    </td>
                    <td>
                      {log?.latitude != 0 ? (
                        <i
                          className="bx bx-map text-danger  cursor-pointer"
                          data-bs-toggle="tooltip"
                          data-bs-offset="0,8"
                          data-bs-placement="top"
                          data-bs-custom-class="tooltip"
                          title="Location"
                          onClick={() =>
                            LocationLink(log?.latitude, log?.longitude)
                          }
                        ></i>
                      ) : (
                        "--"
                      )}
                    </td>
                    <td className="text-wrap">
                      {`${log?.updatedByEmployee?.firstName ?? ""} ${
                        log?.updatedByEmployee?.lastName ?? ""
                      }`}
                    </td>
                    <td className="text-wrap" colSpan={3}>
                      {log?.comment?.length > 50
                        ? `${log.comment.slice(0, 50)}...`
                        : log.comment || "--"}
                    </td>
                  </tr>
                ))}
            </tbody>
          </table>
        </>
      )}
    </div>
  );
};

export default AttendLogs;
