import { Box } from "@mantine/core";
import { Freight } from "@edr/types";

import type { PortalInvoice } from "@/services/invoices.service";

/** Statuses a customer can still pay. */
export const PAYABLE_STATUSES: Freight.InvoiceStatus[] = [
  Freight.InvoiceStatus.Issued,
  Freight.InvoiceStatus.Pending,
  Freight.InvoiceStatus.PartiallyPaid,
  Freight.InvoiceStatus.Overdue,
];

export const isPayable = (status: Freight.InvoiceStatus) =>
  PAYABLE_STATUSES.includes(status);

const STATUS_STYLE: Record<
  Freight.InvoiceStatus,
  { label: string; bg: string; fg: string }
> = {
  [Freight.InvoiceStatus.Draft]: { label: "Draft", bg: "#EEF2F6", fg: "#64748B" },
  [Freight.InvoiceStatus.Issued]: { label: "Due", bg: "#FEF3E2", fg: "#B45309" },
  [Freight.InvoiceStatus.Pending]: { label: "Due", bg: "#FEF3E2", fg: "#B45309" },
  [Freight.InvoiceStatus.PartiallyPaid]: { label: "Partially paid", bg: "#FEF9E7", fg: "#A16207" },
  [Freight.InvoiceStatus.Paid]: { label: "Paid", bg: "#E6F7EF", fg: "#0A6F4D" },
  [Freight.InvoiceStatus.Overdue]: { label: "Overdue", bg: "#FDECEC", fg: "#C0392B" },
  [Freight.InvoiceStatus.Cancelled]: { label: "Cancelled", bg: "#EEF2F6", fg: "#64748B" },
  [Freight.InvoiceStatus.Refunded]: { label: "Refunded", bg: "#EAF1FB", fg: "#2563EB" },
  [Freight.InvoiceStatus.Expired]: { label: "Expired", bg: "#FBEAE7", fg: "#C0392B" },
};

export function InvoiceStatusBadge({ status }: { status: Freight.InvoiceStatus }) {
  const s = STATUS_STYLE[status] ?? { label: status, bg: "#EEF2F6", fg: "#64748B" };
  return (
    <Box
      style={{
        display: "inline-flex",
        alignItems: "center",
        padding: "4px 10px",
        borderRadius: 999,
        background: s.bg,
        color: s.fg,
        fontSize: 12,
        fontWeight: 700,
        whiteSpace: "nowrap",
      }}
    >
      {s.label}
    </Box>
  );
}

export const titleCase = (v: string) =>
  v ? v.charAt(0).toUpperCase() + v.slice(1).toLowerCase() : "—";

/** Best label for who an invoice is billed to (profile ref → profile type → company). */
export function billedTo(inv: PortalInvoice): string {
  const profile = inv.companyProfile;
  if (profile?.reference) return profile.reference;
  if (profile?.type) return titleCase(profile.type);
  return inv.company?.name ?? "—";
}

export const fmtDate = (v: string | null | undefined) =>
  v ? new Date(v).toLocaleDateString() : "—";
