"use client";

import { Badge } from "@/components/ui/badge";
import { TransactionDetailSheet } from "@/components/customer/transaction-detail-sheet";
import type {
  TransactionDetailMetric,
  TransactionRowBase,
} from "@/components/customer/transaction-detail-types";
import { formatAmount } from "@/lib/format/numbers";
import { cn } from "@/lib/utils";

import type { StructuredProductReportRow } from "../../_lib/structured-product-types";

const DETAIL_CONFIG = {
  entityLabel: "Structured product transaction",
  showActions: false,
  accentClassName: "from-rose-500/10 via-transparent to-transparent",
  badgeClassName: "border-0 bg-rose-500/15 font-mono text-rose-700 dark:text-rose-300",
} as const;

function stripHtml(value: string): string {
  return value.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
}

function fieldText(
  row: StructuredProductReportRow,
  field: keyof StructuredProductReportRow["values"],
): string {
  const value = row.values[field];
  if (value == null || value === "") return "";
  return stripHtml(String(value));
}

function fieldDisplay(
  row: StructuredProductReportRow,
  field: keyof StructuredProductReportRow["values"],
): string {
  const text = fieldText(row, field);
  return text || "—";
}

function fieldNumber(
  row: StructuredProductReportRow,
  field: keyof StructuredProductReportRow["values"],
): number | null {
  const raw = row.values[field];
  if (typeof raw === "number") return Number.isFinite(raw) ? raw : null;
  if (typeof raw === "string") {
    const parsed = Number.parseFloat(raw.replace(/,/g, "").replace(/%/g, "").trim());
    return Number.isFinite(parsed) ? parsed : null;
  }
  return null;
}

function plainProductType(row: StructuredProductReportRow): string {
  const fromProduct = stripHtml(row.product.name || "");
  if (fromProduct) return fromProduct;
  return fieldText(row, "product_typeAbsolute") || "Structured Product";
}

function toDetailRow(row: StructuredProductReportRow): TransactionRowBase {
  const productType = plainProductType(row);
  const structureIsin = fieldText(row, "s_isinInit");
  return {
    id: row.id,
    refId: fieldText(row, "AUid1") || structureIsin || row.productId || row.id,
    placementDate: fieldText(row, "TradeDate") || fieldText(row, "SettlementDate"),
    bank: fieldText(row, "s_bname") || "—",
    ticker: structureIsin || fieldText(row, "UnderlyingISIN1") || "—",
    name: productType,
    type: productType,
    executionType: fieldText(row, "Issuer") || "—",
    transaction: productType,
    price: row.raw.notional || fieldNumber(row, "Notional") || 0,
    quantity: 1,
    currency: fieldText(row, "CurrencyName") || "—",
    amount: row.raw.notional || fieldNumber(row, "Notional") || 0,
  };
}

function buildMetrics(row: StructuredProductReportRow): TransactionDetailMetric[] {
  const notional = row.raw.notional || fieldNumber(row, "Notional") || 0;
  const strikePct =
    row.raw.strikePercentage ||
    fieldNumber(row, "StrikePercentage");
  const couponPct = row.raw.couponRate || fieldNumber(row, "Coupon");
  const currency = fieldText(row, "CurrencyName") || null;

  return [
    {
      label: "Notional",
      value: formatAmount(notional),
      sub: currency,
    },
    {
      label: "Strike %",
      value: strikePct != null && strikePct !== 0 ? `${strikePct}` : "—",
      sub: null,
    },
    {
      label: "Coupon",
      value: couponPct != null && couponPct !== 0 ? `${couponPct}%` : "—",
      sub: null,
    },
  ];
}

function AwayValue({ value }: { value: string }) {
  const numeric = Number.parseFloat(value.replace(/,/g, "").replace(/%/g, "").trim());
  const isNeg = Number.isFinite(numeric) && numeric < 0;
  const isPos = Number.isFinite(numeric) && numeric > 0;
  return (
    <span
      className={cn(
        "font-medium tabular-nums",
        isNeg && "text-red-600 dark:text-red-400",
        isPos && "text-emerald-600 dark:text-emerald-400",
      )}
    >
      {value || "—"}
    </span>
  );
}

function UnderlyingCard({ row }: { row: StructuredProductReportRow }) {
  const title = fieldText(row, "Underlying1") || fieldText(row, "UnderlyingISIN1") || "Underlying";
  const isin = fieldText(row, "UnderlyingISIN1");
  const memoryP = Boolean(row.underlyingMeta?.memoryP);
  const memoryPDate = String(row.underlyingMeta?.memoryPDate ?? "").trim() || null;
  const pTitle = memoryPDate
    ? `Autocall memory P since ${memoryPDate}`
    : "Autocall memory P";

  return (
    <li className="rounded-xl border border-border/60 bg-muted/20 px-4 py-3.5">
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0">
          <p className="flex min-w-0 items-center gap-1.5 font-medium text-foreground/90" title={title}>
            <span className="truncate">{title}</span>
            {memoryP ? (
              <span
                className="inline-flex size-5 shrink-0 items-center justify-center rounded border border-emerald-600/50 bg-emerald-500/15 text-[11px] font-bold text-emerald-700"
                title={pTitle}
              >
                P
              </span>
            ) : null}
          </p>
          {memoryP && memoryPDate ? (
            <p className="mt-0.5 text-[10px] text-muted-foreground">P since {memoryPDate}</p>
          ) : null}
          <p className="mt-0.5 font-mono text-[11px] text-muted-foreground tracking-tight">
            {isin || "—"}
          </p>
        </div>
        {fieldText(row, "Industry") ? (
          <Badge variant="secondary" className="shrink-0 rounded-full text-[10px]">
            {fieldText(row, "Industry")}
          </Badge>
        ) : null}
      </div>

      <div className="mt-3 grid grid-cols-2 gap-3 border-t border-border/50 pt-3 text-xs sm:grid-cols-4">
        <div>
          <p className="text-muted-foreground">Initial</p>
          <p className="mt-0.5 font-medium tabular-nums">{fieldDisplay(row, "InitialLevel")}</p>
        </div>
        <div>
          <p className="text-muted-foreground">Strike</p>
          <p className="mt-0.5 font-medium tabular-nums">{fieldDisplay(row, "StrikeLevel")}</p>
        </div>
        <div>
          <p className="text-muted-foreground">CMP</p>
          <p className="mt-0.5 font-medium tabular-nums">{fieldDisplay(row, "CMP")}</p>
        </div>
        <div>
          <p className="text-muted-foreground">KO price</p>
          <p className="mt-0.5 font-medium tabular-nums">
            {fieldText(row, "KOPrice") || String(row.ko_price ?? "") || "—"}
          </p>
        </div>
      </div>

      <div className="mt-3 grid grid-cols-2 gap-3 border-t border-border/50 pt-3 text-xs">
        <div>
          <p className="text-muted-foreground">% away from Initial</p>
          <div className="mt-0.5">
            <AwayValue value={fieldText(row, "away_from_Initial1")} />
          </div>
        </div>
        <div>
          <p className="text-muted-foreground">% away from Strike</p>
          <div className="mt-0.5">
            <AwayValue value={fieldText(row, "away_from_Strike1")} />
          </div>
        </div>
      </div>
    </li>
  );
}

function DetailItem({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-lg px-3 py-2.5">
      <dt className="text-muted-foreground text-xs">{label}</dt>
      <dd className="mt-1 text-sm font-medium">{value || "—"}</dd>
    </div>
  );
}

function StructuredProductExtraContent({
  head,
  underlyings,
}: {
  head: StructuredProductReportRow;
  underlyings: StructuredProductReportRow[];
}) {
  const deliveryLabel = head.delivery ? "Delivered" : "Notional";
  const earlyRedmLabel = head.earlyRedemption ? "Yes" : "No";

  return (
    <div className="space-y-6">
      <div className="rounded-2xl border border-border/60 bg-card p-6 shadow-sm">
        <h3 className="font-semibold text-sm">Structure parameters</h3>
        <p className="mt-0.5 text-muted-foreground text-xs">Product terms and payout flags</p>
        <dl className="mt-5 grid grid-cols-2 gap-2 md:grid-cols-3">
          <DetailItem label="Product type" value={plainProductType(head)} />
          <DetailItem label="Structure ISIN" value={fieldText(head, "s_isinInit")} />
          <DetailItem label="Issuer" value={fieldText(head, "Issuer")} />
          <DetailItem
            label="Strike %"
            value={
              head.raw.strikePercentage
                ? String(head.raw.strikePercentage)
                : fieldText(head, "StrikePercentage")
            }
          />
          <DetailItem
            label="Coupon / rate"
            value={
              head.raw.couponRate
                ? `${head.raw.couponRate}%`
                : fieldText(head, "Coupon")
                  ? `${fieldText(head, "Coupon")}%`
                  : ""
            }
          />
          <DetailItem label="KO barrier" value={fieldText(head, "KOBarrier")} />
          <DetailItem label="Indicative annual coupon" value={fieldText(head, "IndicativeAnnualCoupon")} />
          <DetailItem label="Annual coupon (calc)" value={fieldText(head, "annualCouponCalc")} />
          <DetailItem label="Max coupon" value={fieldText(head, "MaxCoupon")} />
          <DetailItem label="Delivery" value={deliveryLabel} />
          <DetailItem label="Early redemption" value={earlyRedmLabel} />
          <DetailItem label="Maturity / final valuation" value={fieldText(head, "FinalValuationDate")} />
          <DetailItem label="Settlement" value={fieldText(head, "SettlementDate")} />
        </dl>
      </div>

      <div className="rounded-2xl border border-border/60 bg-card p-6 shadow-sm">
        <h3 className="font-semibold text-sm">Underlying details</h3>
        <p className="mt-0.5 text-muted-foreground text-xs">
          {underlyings.length} underlying{underlyings.length === 1 ? "" : "s"} · levels and % away
        </p>
        {underlyings.length === 0 ? (
          <p className="mt-6 py-4 text-center text-muted-foreground text-sm">No underlying records.</p>
        ) : (
          <ul className="mt-5 space-y-3">
            {underlyings.map((leg) => (
              <UnderlyingCard key={leg.id} row={leg} />
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}

export function StructuredProductDetailSheet({
  group,
  open,
  onOpenChange,
}: {
  group: StructuredProductReportRow[] | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const head = group?.[0] ?? null;
  if (!head) {
    return (
      <TransactionDetailSheet
        row={null}
        open={open}
        onOpenChange={onOpenChange}
        config={DETAIL_CONFIG}
      />
    );
  }

  return (
    <TransactionDetailSheet
      row={toDetailRow(head)}
      open={open}
      onOpenChange={onOpenChange}
      config={DETAIL_CONFIG}
      metrics={buildMetrics(head)}
      extraContent={
        <StructuredProductExtraContent head={head} underlyings={group ?? [head]} />
      }
    />
  );
}
