import React from "react";
import { PurchaseOrderStatus } from "../../types/purchase-order";
import { ShipmentStatus } from "../../types/shipment";
import {
  purchaseOrderStatusColors,
  shipmentStatusColors,
  getStatusColor,
} from "../../utils/statusColors";
import {
  UserRole,
  getStatusLabel,
  getStatusColorForRole,
} from "../../utils/roleStatusLabels";

interface StatusBadgeProps {
  status: PurchaseOrderStatus | ShipmentStatus | string;
  className?: string;
  type?: "purchase-order" | "shipment" | "custom";
  customColors?: {
    [key: string]: string;
  };
  role?: UserRole;
}

const StatusBadge: React.FC<StatusBadgeProps> = ({
  status,
  className = "",
  type = "purchase-order",
  customColors,
  role,
}) => {
  // If role is provided and type is purchase-order, use role-based labels and colors
  if (role && type === "purchase-order") {
    const displayLabel = getStatusLabel(status, role);
    const colorClasses = getStatusColorForRole(displayLabel, role);

    return (
      <span
        className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${colorClasses} ${className}`}
      >
        {displayLabel}
      </span>
    );
  }

  // Default behavior for non-role-based or other types
  const getStatusClasses = (status: string) => {
    if (type === "custom" && customColors) {
      return getStatusColor(status, customColors);
    }
    if (type === "shipment") {
      return getStatusColor(status, shipmentStatusColors);
    }
    return getStatusColor(status, purchaseOrderStatusColors);
  };

  const formatStatusText = (status: string) => {
    return status.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
  };

  return (
    <span
      className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${getStatusClasses(
        status
      )} ${className}`}
    >
      {formatStatusText(status)}
    </span>
  );
};

export default StatusBadge;
