import type { SellOrderStatus, SellPermission } from "@/types"

export const sellStatusTone: Record<SellOrderStatus, "neutral" | "pending" | "warning" | "success" | "danger" | "info"> = {
  draft: "neutral",
  pending_review: "pending",
  pending_approval: "warning",
  approved: "success",
  posted: "success",
  delivering: "info",
  delivered: "success",
  rejected: "danger",
  cancelled: "neutral",
  closed: "neutral",
}

export const sellStatusLabel: Record<SellOrderStatus, { en: string; ar: string }> = {
  draft: { en: "Draft", ar: "مسودة" },
  pending_review: { en: "Pending review", ar: "بانتظار المراجعة" },
  pending_approval: { en: "Pending approval", ar: "بانتظار الاعتماد" },
  approved: { en: "Approved", ar: "معتمد" },
  posted: { en: "Posted", ar: "مرحل" },
  delivering: { en: "Delivering", ar: "قيد التسليم" },
  delivered: { en: "Delivered", ar: "تم التسليم" },
  rejected: { en: "Rejected", ar: "مرفوض" },
  cancelled: { en: "Cancelled", ar: "ملغي" },
  closed: { en: "Closed", ar: "مغلق" },
}

export type SellAction = "submit" | "review" | "approve" | "reject" | "cancel" | "post" | "delivering" | "delivered" | "close" | "reverse"

const actionPermission: Record<SellAction, SellPermission> = {
  submit: "sell_orders:update",
  review: "sell_orders:review",
  approve: "sell_orders:approve",
  reject: "sell_orders:review",
  cancel: "sell_orders:cancel",
  post: "sell_orders:post",
  delivering: "sell_orders:update",
  delivered: "sell_orders:update",
  close: "sell_orders:approve",
  reverse: "sell_orders:reverse",
}

const statusActions: Partial<Record<SellOrderStatus, SellAction[]>> = {
  draft: ["submit", "cancel"],
  pending_review: ["review", "reject", "cancel"],
  pending_approval: ["approve", "reject", "cancel"],
  approved: ["post", "cancel"],
  posted: ["delivering", "reverse"],
  delivering: ["delivered", "cancel"],
  delivered: ["close"],
}

export function allowedSellActions(status: SellOrderStatus, permissions: string[] = []) {
  return (statusActions[status] ?? []).filter(action => permissions.includes(actionPermission[action]))
}

export function displayCustomer(customer?: { customer_code?: string | null; full_name_en?: string | null; full_name_ar?: string | null } | null, language = "en") {
  return (language === "ar" ? customer?.full_name_ar : customer?.full_name_en) || customer?.full_name_ar || customer?.full_name_en || customer?.customer_code || "-"
}
