import React, { useState, useEffect } from "react";
import LineChart from "../Charts/LineChart";
import { useProjects } from "../../hooks/useProjects";
import { useDashboard_AttendanceData } from "../../hooks/useDashboard_Data";
import ApexChart from "../Charts/Circle";

const LOCAL_STORAGE_PROJECT_KEY = "selectedAttendanceProjectId";

const Attendance = () => {
  const { projects } = useProjects();
  const today = new Date().toISOString().split("T")[0]; // Format: YYYY-MM-DD
  const [selectedDate, setSelectedDate] = useState(today);
  const storedProjectId = localStorage.getItem(LOCAL_STORAGE_PROJECT_KEY);
  const initialProjectId = storedProjectId || "all";
  const [selectedProjectId, setSelectedProjectId] = useState(initialProjectId);
  const [displayedProjectName, setDisplayedProjectName] =
    useState("Select Project");
  const [activeTab, setActiveTab] = useState("Summary");

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

  useEffect(() => {
    if (selectedProjectId === "all") {
      setDisplayedProjectName("All Projects");
    } else if (projects) {
      const foundProject = projects.find((p) => p.id === selectedProjectId);
      setDisplayedProjectName(
        foundProject ? foundProject.name : "Select Project"
      );
    } else {
      setDisplayedProjectName("Select Project");
    }

    localStorage.setItem(LOCAL_STORAGE_PROJECT_KEY, selectedProjectId);
  }, [selectedProjectId, projects]);

  const handleProjectSelect = (projectId) => {
    setSelectedProjectId(projectId);
  };

  const handleDateChange = (e) => {
    setSelectedDate(e.target.value);
  };

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

          <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={() => handleProjectSelect("all")}
                >
                  All Projects
                </button>
              </li>
              {projects?.map((project) => (
                <li key={project.id}>
                  <button
                    className="dropdown-item"
                    onClick={() => handleProjectSelect(project.id)}
                  >
                    {project.name}
                  </button>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </div>

      <div className="d-flex flex-wrap justify-content-between align-items-center mb-0 mt-0 me-5 ms-5">
        {/* Tabs */}
        <div>
          <ul className="nav nav-tabs " role="tablist">
            <li className="nav-item">
              <button
                type="button"
                className={`nav-link ${
                  activeTab === "Summary" ? "active" : ""
                }`}
                onClick={() => setActiveTab("Summary")}
                data-bs-toggle="tab"
              >
                Summary
              </button>
            </li>
            <li className="nav-item">
              <button
                type="button"
                className={`nav-link ${
                  activeTab === "Details" ? "active" : ""
                }`}
                onClick={() => setActiveTab("Details")}
                data-bs-toggle="tab"
              >
                Details
              </button>
            </li>
          </ul>
        </div>
        {/* ✅ Date Picker Aligned Left with Padding */}
        <div className="ps-6 mb-3 mt-0">
          <div style={{ width: "120px" }}>
            <input
              type="date"
              className="form-control p-1"
              // style={{ fontSize: "1rem" }}
              value={selectedDate}
              onChange={handleDateChange}
            />
          </div>
        </div>
      </div>

      <div className="card-body">
        {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 text-center w-100">
                      <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>
        )}

        {activeTab === "Details" && (
          <div
            className="table-responsive"
            style={{ maxHeight: "300px", overflowY: "auto" }}
          >
            <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 &&
                AttendanceData.attendanceTable.length > 0 ? (
                  AttendanceData.attendanceTable.map((record, index) => (
                    <tr key={index}>
                      <td>
                        {record.firstName} {record.lastName}
                      </td>
                      <td>
                        {new Date(record.inTime).toLocaleTimeString([], {
                          hour: "2-digit",
                          minute: "2-digit",
                        })}
                      </td>
                      <td>
                        {new Date(record.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;
