import React, { useEffect, useState } from "react";
import Breadcrumb from "../../components/common/Breadcrumb";
import InfraPlanning from "../../components/Activities/InfraPlanning";
import { useCurrentService, useProjectName } from "../../hooks/useProjects";
import { useDispatch } from "react-redux";
import { setProjectId } from "../../slices/localVariablesSlice";
import { useSelectedProject } from "../../slices/apiDataManager";
import { useProjectAssignedServices } from "../../hooks/useProjects";
import { setService } from "../../slices/globalVariablesSlice";

const TaskPlanning = () => {
  const selectedProject = useSelectedProject();
  const selectedService = useCurrentService();
  const dispatch = useDispatch();

  const { projectNames = [], loading: projectLoading } = useProjectName();

  const { data, isLoading: servicesLoading } =
    useProjectAssignedServices(selectedProject);

  // Set default project if none selected
  useEffect(() => {
    if (!selectedProject && projectNames.length > 0) {
      dispatch(setProjectId(projectNames[0]?.id));
    }
  }, [projectNames, selectedProject, dispatch]);

  // Loading state
  if (projectLoading) {
    return <div className="text-center py-5">Loading...</div>;
  }
  return (
    <div className="container-fluid">
      <Breadcrumb
        data={[
          { label: "Home", link: "/dashboard" },
          { label: "Daily Task Planning" },
        ]}
      />

      <div className="card py-2 page-min-h">
        <div className="col-sm-4 col-md-3 col-12 px-4 py-2 text-start">
          {data?.length === 0 ? (
            <p className="badge bg-label-secondary m-0">Service not assigned</p>
          ) : (
            <select
              name="DataTables_Table_0_length"
              aria-controls="DataTables_Table_0"
              className="form-select form-select-sm"
              aria-label="Select Service"
              value={selectedService ?? ""}
              onChange={(e) => dispatch(setService(e.target.value))}
            >
              <option value="">All Services</option>
              {!servicesLoading &&
                data?.map((service) => (
                  <option key={service.id} value={service.id}>
                    {service.name}
                  </option>
                ))}
            </select>
          )}
        </div>

        {/* Planning Component */}
        {selectedProject ? (
          <InfraPlanning />
        ) : (
          <div className="text-center py-3">Please select a project</div>
        )}
      </div>
    </div>
  );
};

export default TaskPlanning;
