import { Badge } from "@/components/ui/badge"
import { GrnStatus, HoldStatus } from "@/types/grn"

// Fixed width (not w-fit) so every status pill is the same size regardless of
// label length ("Draft" vs "Confirmed" vs "Available").
const badgeSize = "h-6 w-28 justify-center px-2.5 py-1 text-sm"

function grnClass(status: GrnStatus) {
  if (status === "Draft") return "bg-warning/10 text-warning border-transparent"
  if (status === "Confirmed") return "bg-success/10 text-success border-transparent"
  return "bg-destructive/10 text-destructive border-transparent" // Closed
}

export function GrnStatusBadge({ status }: { status: GrnStatus }) {
  return (
    <Badge variant="outline" className={`${badgeSize} ${grnClass(status)}`}>
      {status}
    </Badge>
  )
}

function holdClass(status: HoldStatus) {
  if (status === "OnHold") return "bg-warning/10 text-warning border-transparent"
  if (status === "Rejected") return "bg-destructive/10 text-destructive border-transparent"
  return "bg-success/10 text-success border-transparent" // Available
}

export function HoldStatusBadge({ status }: { status: HoldStatus }) {
  return (
    <Badge variant="outline" className={`${badgeSize} ${holdClass(status)}`}>
      {status}
    </Badge>
  )
}

export type GrnPaymentStatus = "Unpaid" | "PartiallyPaid" | "Paid"

export function grnPaymentStatus(paidAmount: number, balanceAmount: number): GrnPaymentStatus {
  if (balanceAmount <= 0) return "Paid"
  if (paidAmount > 0) return "PartiallyPaid"
  return "Unpaid"
}

function paymentClass(status: GrnPaymentStatus) {
  if (status === "Paid") return "bg-success/10 text-success border-transparent"
  if (status === "PartiallyPaid") return "bg-warning/10 text-warning border-transparent"
  return "bg-muted text-muted-foreground border-transparent" // Unpaid
}

const paymentLabel: Record<GrnPaymentStatus, string> = {
  Unpaid: "Unpaid",
  PartiallyPaid: "Partial",
  Paid: "Paid",
}

export function GrnPaymentStatusBadge({ paidAmount, balanceAmount }: { paidAmount: number; balanceAmount: number }) {
  const status = grnPaymentStatus(paidAmount, balanceAmount)
  return (
    <Badge variant="outline" className={`${badgeSize} ${paymentClass(status)}`}>
      {paymentLabel[status]}
    </Badge>
  )
}
