import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { useProfile } from "../../hooks/useProfile";
import { DIRECTORY_ADMIN, DIRECTORY_MANAGER } from "../../utils/constants";

const BucketList = ({ buckets, loading, searchTerm, onEdit, onDelete }) => {
  const { profile } = useProfile();
  const IsDirecrory_Admin = useHasUserPermission(DIRECTORY_ADMIN);
  const IsDirectory_Manager = useHasUserPermission(DIRECTORY_MANAGER);
  const sorted = buckets.filter((bucket) =>
    bucket.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  if (loading) return <div>Loading...</div>;
  if (!loading && sorted.length === 0) return <div>No buckets found</div>;

  return (
    <div className="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-3 pt-3 px-2 px-sm-0">
      {sorted.map((bucket) => (
        <div className="col" key={bucket.id}>
          <div className="card h-100">
            <div className="card-body p-4">
              <h6 className="card-title d-flex justify-content-between">
                <span>{bucket.name}</span>
                {(IsDirecrory_Admin ||
                  IsDirectory_Manager ||
                  bucket?.createdBy?.id === profile?.employeeInfo?.id) && (
                  <div className="d-flex gap-2">
                    <i
                      className="bx bx-edit bx-sm text-primary cursor-pointer"
                      onClick={() => onEdit(bucket)}
                    />
                    <i
                      className="bx bx-trash bx-sm text-danger cursor-pointer"
                      onClick={() => onDelete(bucket?.id)}
                    />
                  </div>
                )}
              </h6>
              <h6 className="card-subtitle mb-2 text-muted">
                Contacts: {bucket.numberOfContacts || 0}
              </h6>
              <p className="card-text">
                {bucket.description || "No description"}
              </p>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
};

export default BucketList;
