import { Building2, CalendarDays, ExternalLink, Layers3, Percent } from "lucide-react";

import { Badge } from "@/components/ui/badge";

import {
  RecordViewHeader,
  RecordViewHero,
  RecordViewShell,
} from "@/app/customer/_components/record-view/record-view-layout";
import { RecordViewMutationActions } from "@/app/customer/_components/record-view/record-view-mutation-actions";
import {
  displayValue,
  formatRecordMoney,
  RecordDetailRow,
  RecordExternalLinkRow,
  RecordViewSection,
} from "@/app/customer/_components/record-view/record-view-primitives";
import { CashflowAwayCell } from "@/app/customer/[tenant]/reports/cashflow/_components/cashflow-away-cell";
import type { CashflowIsinUnderlying } from "@/app/customer/[tenant]/reports/cashflow/_lib/cashflow-isin-details-server-api";
import { resolveCashflowStructureReportUrl } from "@/app/customer/[tenant]/reports/cashflow/_lib/resolve-cashflow-structure-report-url";
import { ErrorBanner } from "@/components/shared/error-banner";
import { FRONTEND_ROUTES } from "@/config/frontend-routes";
import { formatApiDate } from "@/lib/format/dates";
import { customerUrl } from "@/lib/tenant";

import type { StructureViewPageData } from "../_lib/fetch-structure-view-page";

type StructureViewPageProps = {
  tenant: string;
  data: StructureViewPageData;
  customerId?: number | null;
  backHref?: string;
};

function UnderlyingCard({
  row,
  away,
  hasAway,
}: {
  row: {
    ticker: string;
    isin: string;
    currency: string;
    spot_price: string;
    strike_price: string;
    quantity: string;
    underlying?: string;
    reference_link?: string;
  };
  away?: CashflowIsinUnderlying | null;
  hasAway: boolean;
}) {
  const title = row.underlying?.trim() || away?.name?.trim() || row.ticker || "Underlying";
  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="truncate font-medium text-foreground/90" title={title}>
            {title}
          </p>
          <p className="mt-0.5 font-mono text-[11px] text-muted-foreground tracking-tight">
            {displayValue(row.isin || away?.isin)}
          </p>
        </div>
        {(row.currency || away?.currency) && (
          <Badge variant="secondary" className="shrink-0 rounded-full">
            {row.currency || away?.currency}
          </Badge>
        )}
      </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">Ticker</p>
          <p className="mt-0.5 font-medium">{displayValue(row.ticker)}</p>
        </div>
        <div>
          <p className="text-muted-foreground">Spot</p>
          <p className="mt-0.5 font-medium tabular-nums">{displayValue(row.spot_price)}</p>
        </div>
        <div>
          <p className="text-muted-foreground">Strike</p>
          <p className="mt-0.5 font-medium tabular-nums">{displayValue(row.strike_price)}</p>
        </div>
        <div>
          <p className="text-muted-foreground">Quantity</p>
          <p className="mt-0.5 font-medium tabular-nums">{displayValue(row.quantity)}</p>
        </div>
      </div>
      {hasAway ? (
        <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>
            <CashflowAwayCell
              value={away?.awayFromInitial ?? null}
              negative={away?.awayFromInitialNegative ?? null}
            />
          </div>
          <div>
            <p className="text-muted-foreground">% Away from Strike</p>
            <CashflowAwayCell
              value={away?.awayFromStrike ?? null}
              negative={away?.awayFromStrikeNegative ?? null}
            />
          </div>
        </div>
      ) : null}
      {row.reference_link?.trim() ? (
        <a
          href={row.reference_link.trim()}
          target="_blank"
          rel="noreferrer"
          className="mt-3 inline-flex items-center gap-1 text-xs text-teal-700 hover:underline dark:text-teal-400"
        >
          Reference
          <ExternalLink className="size-3" />
        </a>
      ) : null}
    </li>
  );
}

export function StructureViewPage({
  tenant,
  data,
  customerId,
  backHref,
}: StructureViewPageProps) {
  const {
    values,
    isinDetails,
    refId,
    transactionLabel,
    currencyLabel,
    bankLabel,
    assetClassLabel,
    assetTypeLabel,
    structureAssetClassLabel,
    errorMessage,
    id,
    issuer,
  } = data;
  const localId = id.split("-")[0] ?? id;

  const listHref = backHref || customerUrl(tenant, "/structure");
  const editHref = customerUrl(tenant, `/structure/form?id=${encodeURIComponent(id)}`);
  const reportHref = resolveCashflowStructureReportUrl({
    tenant,
    isin: values.s_isin,
    clientId: customerId,
  });
  const cashflowHref = customerUrl(tenant, "/reports/cashflow");
  const isin = (values.s_isin || isinDetails?.isin || "").trim();

  const awayByIsin = new Map(
    (isinDetails?.underlyings ?? []).map((row) => [row.isin.trim().toUpperCase(), row]),
  );

  return (
    <RecordViewShell>
      <RecordViewHeader
        tone="rose"
        badgeLabel="Structure"
        extraBadges={
          <>
            <Badge variant="outline" className="rounded-full">
              {transactionLabel}
            </Badge>
            {values.product_type?.trim() ? (
              <Badge variant="secondary" className="rounded-full">
                {values.product_type}
              </Badge>
            ) : null}
          </>
        }
        title={displayValue(
          values.structure_name || isinDetails?.name,
          `Structure #${localId}`,
        )}
        refId={displayValue(refId, localId)}
        isin={isin}
        actions={
          <RecordViewMutationActions
            localId={localId}
            refId={displayValue(refId, localId)}
            listHref={listHref}
            cashflowHref={cashflowHref}
            editHref={editHref}
            reportHref={reportHref}
            reportLabel="Structure report"
            deleteLabel="structure"
            deleteHref={FRONTEND_ROUTES.customerPortal.structure.delete(tenant)}
            successTitle="Structure deleted"
          />
        }
      />

      <ErrorBanner message={errorMessage} />

      {!errorMessage ? (
        <>
          <RecordViewHero
            tone="rose"
            amountLabel="Notional"
            amount={formatRecordMoney(values.amount || values.price, currencyLabel)}
            subtitle={`Strike ${displayValue(values.s_percentage)}${
              values.i_rate?.trim() ? ` · Coupon ${values.i_rate.trim()}%` : ""
            }`}
            leftDate={values.t_date}
            rightDateLabel="Maturity"
            rightDate={values.m_date}
          />

          <div className="grid gap-4 lg:grid-cols-2">
            <RecordViewSection title="Structure details" icon={<Layers3 className="size-4" />}>
              <RecordDetailRow
                label="Name"
                value={displayValue(values.structure_name || isinDetails?.name)}
              />
              <RecordDetailRow label="ISIN" value={displayValue(isin)} mono />
              <RecordDetailRow label="Product type" value={displayValue(values.product_type)} />
              {issuer ? <RecordDetailRow label="Issuer" value={displayValue(issuer)} /> : null}
              <RecordDetailRow
                label="Asset class"
                value={displayValue(assetClassLabel || structureAssetClassLabel)}
              />
              <RecordDetailRow label="Asset type" value={displayValue(assetTypeLabel)} />
              <RecordDetailRow label="KO barrier" value={displayValue(values.ko_barrirer)} />
              <RecordDetailRow
                label="Duration"
                value={
                  values.duration?.trim()
                    ? `${values.duration.trim()}${values.duration_other === "30" ? " months" : ""}`
                    : "—"
                }
              />
            </RecordViewSection>

            <RecordViewSection title="Dates" icon={<CalendarDays className="size-4" />}>
              <RecordDetailRow
                label="Trade date"
                value={formatApiDate(values.t_date, "dd MMM yyyy", values.t_date) || "—"}
              />
              <RecordDetailRow
                label="Maturity date"
                value={formatApiDate(values.m_date, "dd MMM yyyy", values.m_date) || "—"}
              />
              <RecordDetailRow
                label="Observation date"
                value={formatApiDate(values.o_date, "dd MMM yyyy", values.o_date) || "—"}
              />
              <RecordDetailRow
                label="Payment date"
                value={formatApiDate(values.p_date, "dd MMM yyyy", values.p_date) || "—"}
              />
            </RecordViewSection>

            <RecordViewSection title="Pricing" icon={<Percent className="size-4" />}>
              <RecordDetailRow
                label="Currency"
                value={displayValue(currencyLabel)}
              />
              <RecordDetailRow
                label="Price / notional"
                value={formatRecordMoney(values.price, currencyLabel)}
              />
              <RecordDetailRow
                label="Amount"
                value={formatRecordMoney(values.amount, currencyLabel)}
              />
              <RecordDetailRow label="Strike %" value={displayValue(values.s_percentage)} />
              <RecordDetailRow label="Coupon / rate" value={displayValue(values.i_rate)} />
              <RecordDetailRow label="Commission" value={displayValue(values.commission)} />
              <RecordDetailRow label="Charges" value={displayValue(values.b_1)} />
              <RecordDetailRow label="Tax" value={displayValue(values.b_2)} />
            </RecordViewSection>

            <RecordViewSection title="Settlement" icon={<Building2 className="size-4" />}>
              <RecordDetailRow label="Bank" value={displayValue(bankLabel)} />
              <RecordDetailRow label="Reference no." value={displayValue(values.r_no)} />
              <RecordDetailRow label="Purpose" value={displayValue(values.purpose)} />
              <RecordDetailRow label="Remarks" value={displayValue(values.remarks)} />
              {values.r_link?.trim() ? <RecordExternalLinkRow href={values.r_link} /> : null}
            </RecordViewSection>
          </div>

          <section className="rounded-2xl border border-border/60 bg-card/80 p-5 shadow-sm">
            <div className="mb-4 flex flex-wrap items-center justify-between gap-2">
              <div>
                <h2 className="font-semibold text-sm tracking-tight">Underlying details</h2>
                <p className="text-muted-foreground text-xs">
                  Booked underlyings
                  {isinDetails?.hasAway ? " with live % away from cashflow" : ""}
                </p>
              </div>
              {isin ? (
                <Badge variant="outline" className="rounded-full font-mono text-[11px]">
                  {isin}
                </Badge>
              ) : null}
            </div>
            {values.underlyings.length === 0 ? (
              <p className="py-6 text-center text-muted-foreground text-sm">
                No underlying records.
              </p>
            ) : (
              <ul className="space-y-3">
                {values.underlyings.map((row, index) => (
                  <UnderlyingCard
                    key={`${row.isin}-${row.ticker}-${index}`}
                    row={row}
                    away={awayByIsin.get(row.isin.trim().toUpperCase()) ?? null}
                    hasAway={Boolean(isinDetails?.hasAway)}
                  />
                ))}
              </ul>
            )}
          </section>
        </>
      ) : null}
    </RecordViewShell>
  );
}
