import { useMemo } from "react";
import { ArrowDownTrayIcon, ArrowTopRightOnSquareIcon } from "@heroicons/react/24/outline";
import { Formatting } from "@customer-portal/domain/toolkit";
import type { Invoice } from "@customer-portal/domain/billing";
import { Button } from "@/components/atoms/button";
import { StatusPill } from "@/components/atoms/status-pill";
import { cn, formatIsoDate, formatIsoRelative } from "@/shared/utils";

const { formatCurrency } = Formatting;

interface InvoiceSummaryBarProps {
  invoice: Invoice;
  loadingDownload?: boolean;
  loadingPayment?: boolean;
  onDownload?: () => void;
  onPay?: () => void;
}

const statusVariantMap: Partial<
  Record<Invoice["status"], "success" | "warning" | "error" | "neutral">
> = {
  Paid: "success",
  Unpaid: "warning",
  Overdue: "error",
  Cancelled: "neutral",
  Refunded: "neutral",
  Draft: "neutral",
  Pending: "warning",
  Collections: "error",
};

const statusLabelMap: Partial<Record<Invoice["status"], string>> = {
  Paid: "Paid",
  Unpaid: "Unpaid",
  Overdue: "Overdue",
  Refunded: "Refunded",
  Draft: "Draft",
  Cancelled: "Cancelled",
  Pending: "Pending",
  Collections: "Collections",
};

function formatDisplayDate(dateString?: string) {
  if (!dateString) return null;
  const formatted = formatIsoDate(dateString);
  return formatted === "N/A" || formatted === "Invalid date" ? null : formatted;
}

function formatRelativeDue(
  dateString: string | undefined,
  status: Invoice["status"],
  daysOverdue?: number
) {
  if (!dateString) return null;
  if (status === "Paid") return null;

  if (status === "Overdue" && daysOverdue) {
    return `${daysOverdue} day${daysOverdue === 1 ? "" : "s"} overdue`;
  } else if (status === "Unpaid") {
    const relative = formatIsoRelative(dateString);
    if (relative === "N/A" || relative === "Invalid date") return null;
    // Relative formatter already yields "in X ..." for future dates.
    return relative.startsWith("in ") ? `due ${relative}` : `due ${relative}`;
  }

  return null;
}

export function InvoiceSummaryBar({
  invoice,
  loadingDownload,
  loadingPayment,
  onDownload,
  onPay,
}: InvoiceSummaryBarProps) {
  const formattedTotal = useMemo(
    () => formatCurrency(invoice.total, invoice.currency),
    [invoice.currency, invoice.total]
  );

  const dueDisplay = useMemo(() => formatDisplayDate(invoice.dueDate), [invoice.dueDate]);
  const issuedDisplay = useMemo(() => formatDisplayDate(invoice.issuedAt), [invoice.issuedAt]);
  const relativeDue = useMemo(
    () => formatRelativeDue(invoice.dueDate, invoice.status, invoice.daysOverdue),
    [invoice.dueDate, invoice.status, invoice.daysOverdue]
  );

  const statusVariant = statusVariantMap[invoice.status] ?? "neutral";
  const statusLabel = statusLabelMap[invoice.status] ?? invoice.status;

  return (
    <div className="px-6 py-8 sm:px-8">
      {/* Header layout with proper alignment */}
      <div className="flex flex-col gap-6">
        {/* Top row: Amount and Actions */}
        <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-6">
          {/* Left section: Amount, currency, and status */}
          <div className="flex items-center gap-4 flex-wrap">
            <div className="text-4xl sm:text-5xl font-bold text-foreground leading-none">
              {formattedTotal}
            </div>
            <div className="text-base font-medium text-muted-foreground uppercase tracking-wide">
              {invoice.currency?.toUpperCase()}
            </div>
            <StatusPill
              size="md"
              variant={statusVariant}
              label={statusLabel}
              className="font-semibold"
            />
          </div>

          {/* Right section: Actions */}
          <div className="flex flex-row gap-3 flex-shrink-0">
            <Button
              variant="outline"
              onClick={onDownload}
              disabled={!onDownload}
              loading={loadingDownload ?? false}
              leftIcon={<ArrowDownTrayIcon className="h-4 w-4" />}
            >
              Download PDF
            </Button>
            {(invoice.status === "Unpaid" || invoice.status === "Overdue") && (
              <Button
                onClick={onPay}
                disabled={!onPay}
                loading={loadingPayment ?? false}
                rightIcon={<ArrowTopRightOnSquareIcon className="h-4 w-4" />}
                variant="default"
              >
                Pay Now
              </Button>
            )}
          </div>
        </div>

        {/* Bottom row: Due date and Invoice metadata */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 text-sm text-muted-foreground border-t border-border pt-4">
          {/* Due date information */}
          <div className="flex items-center gap-2">
            {dueDisplay && <span>Due {dueDisplay}</span>}
            {relativeDue && (
              <>
                {dueDisplay && <span className="text-muted-foreground/50">•</span>}
                <span
                  className={cn(
                    "font-medium",
                    invoice.status === "Overdue" ? "text-danger" : "text-warning"
                  )}
                >
                  {relativeDue}
                </span>
              </>
            )}
          </div>

          {/* Invoice metadata */}
          <div className="flex items-center gap-2">
            <span className="font-semibold text-foreground">Invoice #{invoice.number}</span>
            {issuedDisplay && (
              <>
                <span className="text-muted-foreground/50">•</span>
                <span>Issued {issuedDisplay}</span>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

export type { InvoiceSummaryBarProps };
