"use client";

import type { ColumnDef } from "@tanstack/react-table";

import { cn } from "@/lib/utils";

import type { UniqueIsinPriceChangeRow } from "./schema";

export function createUniqueIsinPriceChangeColumns(): ColumnDef<UniqueIsinPriceChangeRow>[] {
  return [
    {
      accessorKey: "isin",
      header: "ISIN",
      cell: ({ row }) => (
        <span className="font-mono text-sm font-medium">{row.original.isin}</span>
      ),
    },
    {
      accessorKey: "livePrice",
      header: () => <span className="block w-full text-right">Live Price</span>,
      enableColumnFilter: false,
      cell: ({ row }) => (
        <span className="block text-right font-medium tabular-nums text-sm">
          {row.original.livePrice ?? "—"}
        </span>
      ),
    },
    {
      accessorKey: "marketPriceDate",
      header: "Live Price Date",
      enableColumnFilter: false,
      cell: ({ row }) => (
        <span className="text-sm whitespace-nowrap">
          {row.original.marketPriceDate ?? "—"}
        </span>
      ),
    },
    {
      accessorKey: "previousPrice",
      header: () => (
        <span className="block w-full text-right">Previous Price</span>
      ),
      enableColumnFilter: false,
      cell: ({ row }) => (
        <span className="block text-right font-medium tabular-nums text-sm">
          {row.original.previousPrice ?? "—"}
        </span>
      ),
    },
    {
      accessorKey: "previousPriceDate",
      header: "Previous Price Date",
      enableColumnFilter: false,
      cell: ({ row }) => (
        <span className="text-muted-foreground text-sm whitespace-nowrap">
          {row.original.previousPriceDate ?? "—"}
        </span>
      ),
    },
    {
      accessorKey: "percentageChange",
      header: () => <span className="block w-full text-right">% Change</span>,
      enableColumnFilter: false,
      cell: ({ row }) => (
        <div className="flex justify-end">
          <PercentageChangeBadge value={row.original.percentageChange} />
        </div>
      ),
    },
  ];
}

function PercentageChangeBadge({ value }: { value: number | null }) {
  if (value === null) {
    return <span className="text-sm text-muted-foreground">—</span>;
  }

  const formatted = `${value > 0 ? "+" : ""}${value.toFixed(2)}%`;
  const tone = value > 0 ? "up" : value < 0 ? "down" : "neutral";

  return (
    <span
      className={cn(
        "inline-flex rounded px-2 py-0.5 text-xs font-semibold tabular-nums",
        tone === "up" && "bg-[#d4edda] text-[#155724]",
        tone === "down" && "bg-[#f8d7da] text-[#721c24]",
        tone === "neutral" && "bg-[#e2e3e5] text-[#383d41]",
      )}
    >
      {formatted}
    </span>
  );
}
