"use client";

import type { ColumnDef } from "@tanstack/react-table";
import { Plus } from "lucide-react";
import Link from "next/link";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { formatPrice } from "@/lib/format/numbers";
import { cn } from "@/lib/utils";

import { isSupportedDetailAssetClass } from "./detail-types";
import type { MissingAssetMarketDataRow } from "./schema";

function MarketPriceCell({ row }: { row: MissingAssetMarketDataRow }) {
  if (!row.hasMarketData) {
    return (
      <span className="inline-flex rounded-md bg-destructive/10 px-2 py-1 font-medium text-destructive text-xs">
        No market data
      </span>
    );
  }

  if (row.marketPrice === null || row.marketPrice === 0) {
    return (
      <div className="space-y-1 text-sm">
        <span className="inline-flex rounded-md bg-destructive/10 px-2 py-1 font-medium text-destructive text-xs">
          No price
        </span>
        {row.marketPriceUpdated ? (
          <p className="text-muted-foreground text-xs">
            Updated: {row.marketPriceUpdated}
          </p>
        ) : null}
      </div>
    );
  }

  return (
    <div className="space-y-1 text-sm">
      <span className="font-semibold tabular-nums">
        {formatPrice(row.marketPrice, { minimumFractionDigits: 0, maximumFractionDigits: 6 })}
      </span>
      {row.marketPriceUpdated ? (
        <p className="text-muted-foreground text-xs">
          Updated: {row.marketPriceUpdated}
        </p>
      ) : null}
    </div>
  );
}

function MissingDetailsCell({ row }: { row: MissingAssetMarketDataRow }) {
  const complete = row.missingDetailTags.length === 0;

  if (complete) {
    return (
      <span className="inline-flex rounded-md bg-emerald-50 px-2 py-1 font-medium text-emerald-700 text-xs">
        All details complete
      </span>
    );
  }

  return (
    <div className="max-w-2xl space-y-2">
      <div className="flex flex-wrap gap-1.5">
        {row.missingDetailTags.map((tag) => (
          <Badge
            key={tag}
            variant="outline"
            className="rounded-md bg-background px-2 py-0.5 text-[11px] font-medium leading-5"
          >
            {tag}
          </Badge>
        ))}
      </div>
      <p className="text-muted-foreground text-xs">
        {row.missingDetailTags.length} field{row.missingDetailTags.length === 1 ? "" : "s"} missing
      </p>
    </div>
  );
}

function AddDetailsAction({ row }: { row: MissingAssetMarketDataRow }) {
  if (!isSupportedDetailAssetClass(row.baseAssetClass)) {
    return null;
  }

  const href = `/dashboard/master-table/missing-asset-market-data/add-details?isin=${encodeURIComponent(row.isin)}&asset_class=${encodeURIComponent(row.baseAssetClass)}`;

  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <Button variant="outline" size="sm" className="h-8 gap-1.5 whitespace-nowrap" asChild>
          <Link href={href} aria-label="Add missing details">
            <Plus className="size-3.5" />
            Add details
          </Link>
        </Button>
      </TooltipTrigger>
      <TooltipContent>Add missing details</TooltipContent>
    </Tooltip>
  );
}

const assetClassStyles: Record<MissingAssetMarketDataRow["baseAssetClass"], string> = {
  Stock: "bg-sky-100 text-sky-900",
  Bond: "bg-violet-100 text-violet-900",
  BondFund: "bg-indigo-100 text-indigo-900",
  Commodity: "bg-amber-100 text-amber-900",
  Fx: "bg-emerald-100 text-emerald-900",
};

export const missingAssetMarketDataColumns: ColumnDef<MissingAssetMarketDataRow>[] = [
  {
    accessorKey: "isin",
    header: "ISIN",
    cell: ({ row }) => (
      <span className="block min-w-[150px] font-mono text-sm font-semibold tracking-tight">
        {row.original.isin}
      </span>
    ),
  },
  {
    accessorKey: "baseAssetClass",
    header: "Base asset class",
    cell: ({ row }) => (
      <span
        className={cn(
          "inline-flex rounded-md px-2.5 py-1 text-[11px] font-semibold uppercase tracking-wide",
          assetClassStyles[row.original.baseAssetClass],
        )}
      >
        {row.original.baseAssetClass === "BondFund"
          ? "Bond Fund"
          : row.original.baseAssetClass}
      </span>
    ),
  },
  {
    id: "marketPrice",
    header: "Market price",
    enableColumnFilter: false,
    cell: ({ row }) => <MarketPriceCell row={row.original} />,
  },
  {
    id: "missingDetails",
    header: "Missing details",
    enableColumnFilter: false,
    cell: ({ row }) => <MissingDetailsCell row={row.original} />,
  },
  {
    id: "actions",
    header: () => <span className="block w-full text-right">Actions</span>,
    enableColumnFilter: false,
    cell: ({ row }) => (
      <div className="flex min-w-[120px] justify-end">
        <AddDetailsAction row={row.original} />
      </div>
    ),
    enableSorting: false,
  },
];
