import React from "react";
import { useProjectAssignedOrganizations } from "../../../hooks/useProjects";
import { useSelectedProject } from "../../../slices/apiDataManager";

const ProjectAssignedOrgs = () => {
  const selectedProject = useSelectedProject();
  const { data, isLoading, isError, error } =
    useProjectAssignedOrganizations(selectedProject);

  const orgList = [
    {
      key: "name",
      label: "Organization Name",
      getValue: (org) => (
        <div className="d-flex gap-2 py-1 ">
          <i class="bx bx-buildings"></i>
          <span
            className="text-truncate d-inline-block "
            style={{ maxWidth: "150px" }}
          >
            {org?.name || "N/A"}
          </span>
        </div>
      ),
      align: "text-start",
    },
      {
      key: "service",
      label: "Service Name",
      getValue: (org) => (
        <div className="d-flex gap-2 py-1 ">
        {org?.service?.name}
        </div>
      ),
      align: "text-start",
    },
    {
      key: "sprid",
      label: "Service Provider Id",
      getValue: (org) => (
        <span
          className="text-truncate d-inline-block"
          style={{ maxWidth: "200px" }}
        >
          {org?.sprid || "N/A"}
        </span>
      ),
      align: "text-center",
    },
    {
      key: "isActive",
      label: "Status",
      getValue: (org) => (
        <span
          className={`text-truncate d-inline-block badge bg-label-${org.isActive ? "primary" :"secondary"}`}
          style={{ maxWidth: "80px" }}
        >
          {org?.isActive ? "Active" : "Inactive"}
        </span>
      ),
      align: "text-start",
    },
  ];

  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>{error.message}</div>;

  return (
    <div>
      <div className="dataTables_wrapper no-footer mx-5 pb-2 page">
        <table className="table dataTable text-nowrap">
          <thead>
            <tr className="table_header_border">
              {orgList.map((col) => (
                <th key={col.key} className={col.align}>
                  {col.label}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {Array.isArray(data) && data.length > 0 ? (
              data.map((row, i) => (
                <tr key={i}>
                  {orgList.map((col) => (
                    <td key={col.key} className={col.align}>
                      {col.getValue(row)}
                    </td>
                  ))}
                </tr>
              ))
            ) : (
              <tr style={{ height: "200px" }}>
                <td
                  colSpan={orgList.length}
                  className="text-center align-middle"
                >
                  Not Assigned yet
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default ProjectAssignedOrgs;
