import * as React from "react";
import Link from "next/link";
import { ArrowRight } from "lucide-react";
import { Mono, Stacked } from "@/components/admin/table/cells";
import { cn } from "@/lib/utils";

/**
 * Cells shared by the ops tables (refill, cancel, subscriptions, drip-feed,
 * updates). Server components — build them while mapping DB rows to AdminRow.
 */

/** cuid tail in mono, full value in the tooltip. */
export function TaskIdCell({ id, sub }: { id: string; sub?: React.ReactNode }) {
  const tail = id.length > 8 ? id.slice(-8) : id;
  return (
    <Stacked
      main={
        <span title={id} className="font-mono text-sm font-medium">
          {tail}
        </span>
      }
      sub={sub}
    />
  );
}

/** `#123` linking into /admin/orders filtered on that exact order id. */
export function OrderRefCell({
  orderId,
  sub,
}: {
  orderId: number;
  sub?: React.ReactNode;
}) {
  return (
    <Stacked
      main={
        <Link
          href={`/admin/orders?q=${orderId}&qf=id`}
          className="font-mono text-sm font-medium hover:underline"
        >
          #{orderId}
        </Link>
      }
      sub={sub}
    />
  );
}

/** "0.90000 → 1.20000" with the direction coloured. */
export function RateChangeCell({
  oldRate,
  newRate,
  tone,
}: {
  oldRate: string | null;
  newRate: string | null;
  tone?: "up" | "down" | "neutral";
}) {
  if (!oldRate && !newRate) return <span className="text-muted-foreground">—</span>;
  return (
    <span className="inline-flex items-center gap-1.5 whitespace-nowrap">
      <Mono className="text-muted-foreground">{oldRate ?? "—"}</Mono>
      <ArrowRight className="size-3 shrink-0 opacity-50" />
      <Mono
        className={cn(
          "font-medium",
          tone === "up" && "text-rose-600 dark:text-rose-400",
          tone === "down" && "text-emerald-600 dark:text-emerald-400",
        )}
      >
        {newRate ?? "—"}
      </Mono>
    </span>
  );
}

/** "12 – 40" style range for subscription min/max. */
export function RangeCell({ min, max }: { min: number; max: number }) {
  return (
    <Mono>
      {min}
      <span className="text-muted-foreground"> – </span>
      {max}
    </Mono>
  );
}
