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

import { RecordViewMutationActions } from "@/app/customer/_components/record-view/record-view-mutation-actions";
import {
  RecordViewHeader,
  RecordViewHero,
  RecordViewShell,
} from "@/app/customer/_components/record-view/record-view-layout";
import {
  displayValue,
  formatRecordMoney,
  RecordDetailRow,
  RecordExternalLinkRow,
  RecordViewSection,
} from "@/app/customer/_components/record-view/record-view-primitives";
import {
  currencyCodeFromSecurityText,
  knownCurrencyLabel,
  knownOptionTypeLabel,
  knownTransactionLabel,
} from "@/app/customer/_lib/known-yii-master-labels";
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 { StockOptionViewPageData } from "../_lib/fetch-stock-option-view-page";

type StockOptionViewPageProps = {
  tenant: string;
  data: StockOptionViewPageData;
  backHref?: string;
};

export function StockOptionViewPage({ tenant, data, backHref }: StockOptionViewPageProps) {
  const {
    values,
    refId,
    errorMessage,
    id,
    bankLabel,
    currencyLabel,
    optionTypeLabel,
    transactionLabel,
    optionStyleLabel,
  } = data;
  const localId = id.split("-")[0] ?? id;
  const listHref = backHref || customerUrl(tenant, "/stock");
  const editHref = customerUrl(
    tenant,
    `/stock/form?id=${encodeURIComponent(localId)}&child=option`,
  );
  const cashflowHref = customerUrl(tenant, "/reports/cashflow");

  const resolvedCurrency =
    currencyLabel ||
    knownCurrencyLabel(values?.p_currency || values?.currency) ||
    currencyCodeFromSecurityText(values?.isin, values?.ticker);
  const resolvedOptionType = optionTypeLabel || knownOptionTypeLabel(values?.t_o_o);
  const resolvedTransaction =
    transactionLabel || knownTransactionLabel(values?.transaction);

  return (
    <RecordViewShell>
      <RecordViewHeader
        tone="orange"
        badgeLabel="Stock option"
        title={displayValue(values?.ticker || values?.isin, `Option #${localId}`)}
        refId={displayValue(refId, localId)}
        isin={values?.isin}
        actions={
          <RecordViewMutationActions
            localId={localId}
            refId={displayValue(refId, localId)}
            listHref={listHref}
            cashflowHref={cashflowHref}
            editHref={editHref}
            deleteLabel="stock option"
            deleteHref={FRONTEND_ROUTES.customerPortal.stock.optionDelete(tenant)}
            successTitle="Stock option deleted"
          />
        }
      />

      <ErrorBanner message={errorMessage} />

      {!errorMessage && values ? (
        <>
          <RecordViewHero
            tone="orange"
            amount={formatRecordMoney(values.amount, resolvedCurrency || undefined)}
            subtitle={`Qty ${displayValue(values.quantity)} · Strike ${displayValue(values.price)}`}
            leftDate={values.t_date}
            rightDateLabel="Maturity"
            rightDate={values.m_date}
          />

          <div className="grid gap-4 lg:grid-cols-2">
            <RecordViewSection title="Option details" icon={<Layers3 className="size-4" />}>
              <RecordDetailRow label="Ticker" value={displayValue(values.ticker)} />
              <RecordDetailRow label="ISIN" value={displayValue(values.isin)} mono />
              <RecordDetailRow label="Call / Put" value={displayValue(resolvedOptionType)} />
              <RecordDetailRow label="Transaction" value={displayValue(resolvedTransaction)} />
              <RecordDetailRow label="Style" value={displayValue(optionStyleLabel)} />
              <RecordDetailRow label="Premium" value={displayValue(values.premium)} />
            </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="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(resolvedCurrency)} />
              <RecordDetailRow label="Strike" value={displayValue(values.price)} />
              <RecordDetailRow label="Spot" value={displayValue(values.t_price)} />
              <RecordDetailRow label="Quantity" value={displayValue(values.quantity)} />
              <RecordDetailRow
                label="Amount"
                value={formatRecordMoney(values.amount, resolvedCurrency || undefined)}
              />
              <RecordDetailRow label="Commission" value={displayValue(values.commission)} />
            </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>
        </>
      ) : null}
    </RecordViewShell>
  );
}
