import type { BuyOrderStatus, BuyPermission } from "@/types"

export const buyStatusTone: Record<BuyOrderStatus, "neutral" | "pending" | "warning" | "success" | "danger" | "info"> = {
  draft: "neutral",
  pending_review: "pending",
  pending_approval: "warning",
  approved: "success",
  posted: "success",
  sent_to_supplier: "info",
  partially_supplied: "warning",
  fully_supplied: "success",
  rejected: "danger",
  cancelled: "neutral",
  closed: "neutral",
}

export const buyStatusLabel: Record<BuyOrderStatus, { 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: "مرحل" },
  sent_to_supplier: { en: "Sent to supplier", ar: "مرسل للمورد" },
  partially_supplied: { en: "Partially supplied", ar: "مورد جزئيا" },
  fully_supplied: { en: "Fully supplied", ar: "مورد بالكامل" },
  rejected: { en: "Rejected", ar: "مرفوض" },
  cancelled: { en: "Cancelled", ar: "ملغي" },
  closed: { en: "Closed", ar: "مغلق" },
}

export const buyTypeLabel: Record<string, { en: string; ar: string }> = {
  supplier: { en: "Supplier purchase", ar: "شراء من مورد" },
  customer_buyback: { en: "Customer buyback", ar: "شراء من عميل" },
}

export type BuyAction =
  | "submit"
  | "review"
  | "approve"
  | "reject"
  | "cancel"
  | "post"
  | "send"
  | "partial"
  | "full"
  | "close"
  | "post-supply"
  | "post-buyback"
  | "reverse"
  | "recalculate"

const actionPermission: Record<BuyAction, BuyPermission> = {
  submit: "buy_orders:update",
  review: "buy_orders:review",
  approve: "buy_orders:approve",
  reject: "buy_orders:review",
  cancel: "buy_orders:cancel",
  post: "buy_orders:post",
  send: "buy_orders:approve",
  partial: "buy_orders:update",
  full: "buy_orders:update",
  close: "buy_orders:approve",
  "post-supply": "buy_orders:post",
  "post-buyback": "buy_orders:post",
  reverse: "buy_orders:reverse",
  recalculate: "buy_orders:update",
}

const statusActions: Partial<Record<BuyOrderStatus, BuyAction[]>> = {
  draft: ["recalculate", "submit", "cancel"],
  pending_review: ["review", "reject", "cancel"],
  pending_approval: ["approve", "reject", "cancel"],
  approved: ["send", "post", "post-buyback", "cancel"],
  posted: ["send", "reverse"],
  sent_to_supplier: ["partial", "cancel"],
  partially_supplied: ["full", "post-supply", "cancel"],
  fully_supplied: ["post-supply", "close"],
}

export function allowedBuyActions(status: BuyOrderStatus, permissions: string[] = [], orderType?: string) {
  return (statusActions[status] ?? [])
    .filter(action => orderType === "customer_buyback" ? !["send", "partial", "full", "post-supply"].includes(action) : action !== "post-buyback")
    .filter(action => permissions.includes(actionPermission[action]))
}

export function buyWorkflowPermissionsForUser(user?: {
  user_type?: string | null
  role?: string | null
  roles?: Array<{ code?: string | null }> | null
  permissions?: string[] | null
} | null) {
  const permissions = new Set(user?.permissions || [])
  const roles = new Set([
    user?.role,
    ...(user?.roles || []).map(role => role.code),
  ].filter(Boolean))

  if (user?.user_type === "admin" || roles.has("super_admin")) {
    return [
      ...permissions,
      "buy_orders:read",
      "buy_orders:create",
      "buy_orders:update",
      "buy_orders:review",
      "buy_orders:approve",
      "buy_orders:post",
      "buy_orders:cancel",
      "buy_orders:reverse",
      "buy_orders:attachments",
      "buy_orders:print",
    ]
  }

  if (roles.has("operations_manager")) {
    return [...permissions, "buy_orders:read", "buy_orders:create", "buy_orders:update", "buy_orders:review", "buy_orders:cancel", "buy_orders:attachments", "buy_orders:print"]
  }

  if (roles.has("finance_officer")) {
    return [...permissions, "buy_orders:read", "buy_orders:review", "buy_orders:approve", "buy_orders:post", "buy_orders:cancel", "buy_orders:reverse", "buy_orders:print"]
  }

  if (roles.has("warehouse_admin")) {
    return [...permissions, "buy_orders:read", "buy_orders:update", "buy_orders:post", "buy_orders:attachments", "buy_orders:print"]
  }

  return [...permissions]
}

export function partyLabel(order: { buy_order_type?: string | null; supplier_id?: string | null; customer_id?: string | null; supplier?: { name_en?: string | null; name_ar?: string | null; code?: string | null } | null; customer?: { customer_code?: string | null; full_name_en?: string | null; full_name_ar?: string | null } | null }, language = "en") {
  if (order.buy_order_type === "customer_buyback") {
    return (language === "ar" ? order.customer?.full_name_ar : order.customer?.full_name_en) || order.customer?.customer_code || order.customer_id || "-"
  }
  return (language === "ar" ? order.supplier?.name_ar : order.supplier?.name_en) || order.supplier?.code || order.supplier_id || "-"
}

