"use client";

import type { CSSProperties } from "react";

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

import { isStructureReportAsset } from "../../_lib/cashflow-asset-class";
import type { CashflowEvent, CashflowUnderlying } from "./schema";
import { CashflowEventHoverCard } from "./cashflow-event-hover-card";
import { CashflowStructureStatusIcon } from "./cashflow-structure-status-icon";
import { isCashflowFieldVisible } from "./cashflow-fields-catalog";
import { formatCompactAmount, isNegativeAmount } from "./utils";

type CashflowEventChipProps = {
  event: CashflowEvent;
  compact?: boolean;
  /** Single-line chip for dashboard calendar cells. */
  minimal?: boolean;
  onClick?: () => void;
  className?: string;
  /** Calendar chip visibility prefs. */
  chipVisibility?: Record<string, boolean>;
  /** Hover detail body visibility prefs (independent of chips). */
  detailVisibility?: Record<string, boolean>;
  detailOrder?: string[];
};

function UnderlyingChipRows({
  underlyings,
  showName,
  showIsin,
  showCurrency,
  compact,
}: {
  underlyings: CashflowUnderlying[] | undefined;
  showName: boolean;
  showIsin: boolean;
  showCurrency: boolean;
  compact?: boolean;
}) {
  if (!underlyings?.length || (!showName && !showIsin && !showCurrency)) {
    return null;
  }

  return (
    <div className={cn("space-y-1", compact ? "mt-0.5" : "mt-1")}>
      {underlyings.map((row, index) => {
        const isinPart = showIsin && row.isin ? row.isin : "";
        const currencyPart =
          showCurrency && row.currency ? `(${row.currency})` : "";
        const line2 = [isinPart, currencyPart].filter(Boolean).join(" ");
        if ((!showName || !row.name) && !line2) return null;

        return (
          <div
            key={`${row.isin || row.name || "u"}-${index}`}
            className="min-w-0 space-y-0 leading-snug"
          >
            {showName && row.name ? (
              <p
                className={cn(
                  "truncate text-foreground/85",
                  compact ? "text-[9px]" : "text-[10px]",
                )}
              >
                {row.name}
              </p>
            ) : null}
            {line2 ? (
              <p
                className={cn(
                  "truncate font-mono text-foreground/70",
                  compact ? "text-[9px]" : "text-[10px]",
                )}
              >
                {line2}
              </p>
            ) : null}
          </div>
        );
      })}
    </div>
  );
}

export function CashflowEventChip({
  event,
  compact,
  minimal,
  onClick,
  className,
  chipVisibility,
  detailVisibility,
  detailOrder,
}: CashflowEventChipProps) {
  const show = (key: string) => isCashflowFieldVisible(chipVisibility, key);
  const amountText =
    event.amount || event.currency
      ? formatCompactAmount(event.amount, event.currency) || event.amountDisplay
      : event.amountDisplay;
  const negative = isNegativeAmount(event.amount);
  const isStructure = isStructureReportAsset(event.assetClassCode);
  const tickerShown =
    show("ticker") && event.ticker && event.ticker !== event.isin ? event.ticker : null;
  const underlyingBlock = (
    <UnderlyingChipRows
      underlyings={event.underlyings}
      showName={show("underlyingName")}
      showIsin={show("underlyingIsin")}
      showCurrency={show("underlyingCurrency")}
      compact={compact}
    />
  );

  if (minimal) {
    const minimalChip = (
      <button
        type="button"
        onClick={onClick}
        className="flex w-full items-center gap-1 rounded px-0.5 py-0.5 text-left transition-colors hover:bg-muted/50"
      >
        {isStructure && show("structureStatus") ? (
          <CashflowStructureStatusIcon
            earlyRedemption={event.earlyRedemption}
            delivery={event.delivery}
            size="xs"
            className="shrink-0"
          />
        ) : (
          <span
            className="size-1.5 shrink-0 rounded-full"
            style={{ backgroundColor: event.color || "var(--chart-2)" }}
          />
        )}
        {show("type") ? (
          <span className="min-w-0 truncate text-[8px] font-semibold uppercase tracking-wide text-foreground/85">
            {event.shortLabel}
          </span>
        ) : null}
        {show("amount") && amountText ? (
          <span
            className={cn(
              "ml-auto shrink-0 text-[8px] font-medium tabular-nums",
              negative ? "text-rose-600 dark:text-rose-400" : "text-foreground/80",
            )}
          >
            {amountText}
          </span>
        ) : null}
      </button>
    );

    return (
      <CashflowEventHoverCard
        event={event}
        side="top"
        fieldVisibility={detailVisibility}
        fieldOrder={detailOrder}
      >
        {minimalChip}
      </CashflowEventHoverCard>
    );
  }

  const chipStyle = {
    "--chip-bg": event.color || "#99f6e4",
    "--chip-fg": event.textColor || "#0f766e",
    "--chip-label": "color-mix(in srgb, var(--chip-fg) 28%, #0f172a)",
    "--chip-label-dark": "color-mix(in srgb, var(--chip-fg) 30%, #f8fafc)",
  } as CSSProperties;

  const chip = (
    <button
      type="button"
      onClick={onClick}
      style={chipStyle}
      className={cn(
        "group relative box-border w-full overflow-hidden rounded-md text-left bg-clip-padding",
        "border border-[color-mix(in_srgb,var(--chip-bg)_55%,#94a3b8)]",
        "bg-[color-mix(in_srgb,var(--chip-bg)_22%,white)]",
        "shadow-[0_1px_0_rgba(15,23,42,0.04)]",
        "transition-[transform,box-shadow,background-color] duration-150",
        "hover:-translate-y-px hover:shadow-sm",
        "dark:bg-[color-mix(in_srgb,var(--chip-bg)_28%,black)]",
        "dark:border-[color-mix(in_srgb,var(--chip-bg)_45%,#64748b)]",
        compact ? "px-1.5 py-1" : "px-2.5 py-2",
        className,
      )}
    >
      <span
        aria-hidden
        className="absolute inset-y-0 left-0 w-[3px] rounded-l-md"
        style={{ backgroundColor: event.color }}
      />

      <div className="flex items-center gap-1 pl-1.5">
        {isStructure && show("structureStatus") ? (
          <CashflowStructureStatusIcon
            earlyRedemption={event.earlyRedemption}
            delivery={event.delivery}
            size={compact ? "sm" : "md"}
          />
        ) : null}
        {show("type") ? (
          <span
            className={cn(
              "truncate font-semibold uppercase tracking-[0.1em] text-[color:var(--chip-label)] dark:text-[color:var(--chip-label-dark)]",
              compact ? "text-[9px]" : "text-[10px]",
            )}
          >
            {event.shortLabel}
          </span>
        ) : null}
        {!compact && show("refId") && event.refId ? (
          <span className="truncate text-[10px] text-foreground/70">#{event.refId}</span>
        ) : null}
      </div>

      {show("amount") && amountText ? (
        <p
          className={cn(
            "mt-0.5 truncate pl-1.5 font-semibold tabular-nums tracking-tight",
            compact ? "text-[10px]" : "text-[11px]",
            negative ? "text-rose-950 dark:text-rose-300" : "text-foreground",
          )}
        >
          {amountText}
        </p>
      ) : null}

      {show("currency") && !show("amount") && event.currency ? (
        <p
          className={cn(
            "mt-0.5 truncate pl-1.5 font-medium tabular-nums text-foreground/80",
            compact ? "text-[9px]" : "text-[10px]",
          )}
        >
          {event.currency}
        </p>
      ) : null}

      {!compact ? (
        <div className="mt-1 space-y-0.5 pl-1.5">
          {show("user") && (event.userLabel || event.uidTitle) ? (
            <p className="truncate text-[10px] text-foreground/85">{event.userLabel || event.uidTitle}</p>
          ) : null}
          {show("isin") && event.isin ? (
            <p className="truncate font-mono text-[10px] text-foreground/75">{event.isin}</p>
          ) : null}
          {tickerShown ? (
            <p className="truncate font-mono text-[10px] text-foreground/70">{tickerShown}</p>
          ) : null}
          {show("name") && event.name ? (
            <p className="line-clamp-2 text-[10px] text-foreground/75 leading-snug">{event.name}</p>
          ) : null}
          {show("coupon") && event.coupon ? (
            <p className="truncate text-[10px] text-foreground/70">Coupon {event.coupon}</p>
          ) : null}
          {show("periodicAmount") && event.periodicAmount ? (
            <p className="truncate text-[10px] text-foreground/70">Periodic {event.periodicAmount}</p>
          ) : null}
          {underlyingBlock}
        </div>
      ) : null}

      {compact ? (
        <div className="mt-0.5 space-y-0.5 pl-1.5">
          {show("user") && (event.userLabel || event.uidTitle) ? (
            <p className="truncate text-[9px] text-foreground/85">{event.userLabel || event.uidTitle}</p>
          ) : null}
          {show("isin") && event.isin ? (
            <p className="truncate font-mono text-[9px] text-foreground/75">{event.isin}</p>
          ) : null}
          {tickerShown ? (
            <p className="truncate font-mono text-[9px] text-foreground/70">{tickerShown}</p>
          ) : null}
          {!amountText && show("name") && event.name ? (
            <p className="truncate text-[9px] text-foreground/75">{event.name}</p>
          ) : null}
          {show("coupon") && event.coupon ? (
            <p className="truncate text-[9px] text-foreground/70">Coupon {event.coupon}</p>
          ) : null}
          {show("periodicAmount") && event.periodicAmount ? (
            <p className="truncate text-[9px] text-foreground/70">Periodic {event.periodicAmount}</p>
          ) : null}
          {underlyingBlock}
        </div>
      ) : null}
    </button>
  );

  return (
    <CashflowEventHoverCard
      event={event}
      side={compact ? "top" : "right"}
      fieldVisibility={detailVisibility}
      fieldOrder={detailOrder}
    >
      {chip}
    </CashflowEventHoverCard>
  );
}
