import React, { useState, useMemo } from "react";
import ApexChart from "../Charts/Circle";
import { useProjects } from "../../hooks/useProjects";
import { useDashboard_AttendanceData } from "../../hooks/useDashboard_Data";
import { useSelectedProject } from "../../hooks/useSelectedProject"; // ✅ your custom hook

const Attendance = () => {
  const { projects } = useProjects();
  const today = new Date().toISOString().split("T")[0]; // YYYY-MM-DD
  const [selectedDate, setSelectedDate] = useState(today);

  //  central project selection hook
const selectedProjectId = useSelectedProject()

  const {
    dashboard_Attendancedata: AttendanceData,
    isLoading,
    error: isError,
  } = useDashboard_AttendanceData(selectedDate, selectedProjectId);

  // project name derived once
  const displayedProjectName = useMemo(() => {
    if (selectedProjectId === "all") return "All Projects";
    const found = projects?.find((p) => p.id === selectedProjectId);
    return found?.name || "Select Project";
  }, [selectedProjectId, projects]);

  return (
    <div className="card h-100">
      {/* Header */}
      <div className="card-header mb-1 pb-0">
        <div className="d-flex flex-wrap justify-content-between align-items-center">
          <div className="card-title mb-0 text-start">
            <h5 className="mb-1">Attendance</h5>
            <p className="card-subtitle">Daily Attendance Data</p>
          </div>

          {/* Project Dropdown */}
          <div className="btn-group">
            <button
              className="btn btn-outline-primary btn-sm dropdown-toggle"
              type="button"
              data-bs-toggle="dropdown"
              aria-expanded="false"
            >
              {displayedProjectName}
            </button>
            <ul className="dropdown-menu">
              <li>
                <button
                  className="dropdown-item"
                  onClick={() => setSelectedProjectId("all")}
                >
                  All Projects
                </button>
              </li>
              {projects?.map((project) => (
                <li key={project.id}>
                  <button
                    className="dropdown-item"
                    onClick={() => setSelectedProjectId(project.id)}
                  >
                    {project.name}
                  </button>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </div>

      {/* Tabs + Date Picker */}
      <div className="d-flex flex-wrap justify-content-between align-items-center me-5 ms-5">
        <ul className="nav nav-tabs">
          <li className="nav-item">
            <button
              type="button"
              className={`nav-link ${AttendanceData?.activeTab === "Summary" ? "active" : ""}`}
              onClick={() => (AttendanceData.activeTab = "Summary")}
            >
              Summary
            </button>
          </li>
          <li className="nav-item">
            <button
              type="button"
              className={`nav-link ${AttendanceData?.activeTab === "Details" ? "active" : ""}`}
              onClick={() => (AttendanceData.activeTab = "Details")}
            >
              Details
            </button>
          </li>
        </ul>
        <div className="ps-6 mb-3">
          <input
            type="date"
            className="form-control p-1"
            style={{ width: "120px" }}
            value={selectedDate}
            onChange={(e) => setSelectedDate(e.target.value)}
          />
        </div>
      </div>

      {/* Body */}
      <div className="card-body">
        {/* Summary */}
        {AttendanceData?.activeTab === "Summary" && (
          <div className="row justify-content-center">
            <div className="col-12 col-md-6 d-flex flex-column align-items-center text-center mb-4">
              {isLoading ? (
                <p>Loading Attendance data...</p>
              ) : isError ? (
                <p>No data available.</p>
              ) : (
                AttendanceData && (
                  <>
                    <h5 className="fw-bold mb-0">
                      <i className="bx bx-task text-info"></i> Attendance
                    </h5>
                    <h4 className="mb-0 fw-bold">
                      {AttendanceData.checkedInEmployee?.toLocaleString()}/
                      {AttendanceData.assignedEmployee?.toLocaleString()}
                    </h4>
                    <small className="text-muted">Checked-In / Assigned</small>
                    <div style={{ maxWidth: "180px" }}>
                      <ApexChart
                        completed={AttendanceData.checkedInEmployee}
                        planned={AttendanceData.assignedEmployee}
                      />
                    </div>
                  </>
                )
              )}
            </div>
          </div>
        )}

        {/* Details */}
        {AttendanceData?.activeTab === "Details" && (
          <div className="table-responsive" style={{ maxHeight: "300px" }}>
            <table className="table table-hover mb-0 text-start">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Checkin</th>
                  <th>Checkout</th>
                </tr>
              </thead>
              <tbody>
                {AttendanceData?.attendanceTable?.length ? (
                  AttendanceData.attendanceTable.map((r, i) => (
                    <tr key={i}>
                      <td>{r.firstName} {r.lastName}</td>
                      <td>{r.inTime ? new Date(r.inTime).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : "-"}</td>
                      <td>{r.outTime ? new Date(r.outTime).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : "-"}</td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan="3" className="text-center">No attendance data available</td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
};

export default Attendance;
