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 { ErrorBanner } from "@/components/shared/error-banner";
import { FRONTEND_ROUTES } from "@/config/frontend-routes";
import { formatApiDate } from "@/lib/format/dates";
import { parseBackendNumber, parseBackendNumberOrNull } from "@/lib/format/numbers";
import { customerUrl } from "@/lib/tenant";

import type { InterestDividendViewPageData } from "../_lib/fetch-interest-dividend-view-page";

type InterestDividendViewPageProps = {
  tenant: string;
  data: InterestDividendViewPageData;
  backHref?: string;
};

function formatLinkedNumber(value: string | number): string {
  if (value == null || String(value).trim() === "") return "—";
  // A value the backend sent but that is not a number shows as received rather than as 0.
  const n = parseBackendNumberOrNull(value);
  if (n === null) return displayValue(value);
  return n.toLocaleString("en-US", {
    minimumFractionDigits: 0,
    maximumFractionDigits: 6,
  });
}

export function InterestDividendViewPage({
  tenant,
  data,
  backHref,
}: InterestDividendViewPageProps) {
  const {
    values,
    refId,
    displayName,
    bankLabel,
    transactionCategoryLabel,
    interestSourceTypeLabel,
    interestModeLabel,
    priceLabel,
    linkedTransactions,
    canDelete,
    errorMessage,
    id,
  } = data;
  const localId = id.split("-")[0] ?? id;
  const customerIdFromComposite = (() => {
    if (!id.includes("-")) return null;
    const n = Number(id.split("-")[1] || 0);
    return Number.isFinite(n) && n > 0 ? n : null;
  })();
  const listHref = backHref || customerUrl(tenant, "/interest-dividend");
  const editHref = customerUrl(
    tenant,
    `/interest-dividend/form?id=${encodeURIComponent(id)}`,
  );
  const cashflowHref = customerUrl(tenant, "/reports/cashflow");
  const hasLinkedTransactions = linkedTransactions.length > 0;
  const linkedQtyTotal = linkedTransactions.reduce(
    (sum, row) => sum + parseBackendNumber(row.quantity),
    0,
  );
  const linkedLineTotal = linkedTransactions.reduce((sum, row) => sum + row.lineTotal, 0);
  const heroAmount = hasLinkedTransactions
    ? linkedLineTotal
    : (values?.net ?? values?.amount ?? values?.price);

  return (
    <RecordViewShell>
      <RecordViewHeader
        tone="teal"
        badgeLabel="Interest / dividend"
        title={displayValue(displayName, `Interest / dividend #${localId}`)}
        refId={displayValue(refId, localId)}
        isin={values?.isin || values?.isin_pseudo}
        actions={
          <RecordViewMutationActions
            localId={localId}
            refId={displayValue(refId, localId)}
            listHref={listHref}
            cashflowHref={cashflowHref}
            editHref={editHref}
            canDelete={canDelete}
            deleteLabel="interest / dividend"
            deleteHref={FRONTEND_ROUTES.customerPortal.interestDividend.delete(tenant)}
            deleteId={id}
            deleteCustomerId={customerIdFromComposite}
            successTitle="Interest / dividend deleted"
          />
        }
      />

      <ErrorBanner message={errorMessage} />

      {!errorMessage && values ? (
        <>
          <RecordViewHero
            tone="teal"
            amount={formatRecordMoney(heroAmount)}
            subtitle={
              hasLinkedTransactions
                ? `${linkedTransactions.length} linked transaction${linkedTransactions.length === 1 ? "" : "s"}`
                : `Qty ${displayValue(values.quantity)} · Amount ${displayValue(values.price)}`
            }
            leftDateLabel="Placement date"
            leftDate={values.t_date}
          />

          <div className="grid gap-4 lg:grid-cols-2">
            <RecordViewSection
              title="Interest / dividend details"
              icon={<Layers3 className="size-4" />}
            >
              <RecordDetailRow
                label="Transaction type"
                value={displayValue(transactionCategoryLabel || values.d_p)}
              />
              <RecordDetailRow
                label="Type"
                value={displayValue(interestSourceTypeLabel || values.d_type)}
              />
              <RecordDetailRow
                label="Interest type"
                value={displayValue(interestModeLabel || values.md)}
              />
              <RecordDetailRow
                label="Parent transaction"
                value={displayValue(values.parent_transaction_label || values.parent_id)}
              />
              <RecordDetailRow
                label="Security"
                value={displayValue(values.security_label || values.ticker)}
              />
              <RecordDetailRow label="ISIN" value={displayValue(values.isin)} mono />
              <RecordDetailRow
                label="Currency code"
                value={displayValue(values.isin_pseudo)}
                mono
              />
            </RecordViewSection>

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

            {!hasLinkedTransactions ? (
              <RecordViewSection title="Amounts" icon={<Percent className="size-4" />}>
                <RecordDetailRow label="Quantity" value={displayValue(values.quantity)} />
                <RecordDetailRow label={priceLabel} value={displayValue(values.price)} />
                <RecordDetailRow label="Total" value={formatRecordMoney(values.amount)} />
                <RecordDetailRow label="Commission" value={displayValue(values.commission)} />
                <RecordDetailRow label="Net" value={formatRecordMoney(values.net)} />
              </RecordViewSection>
            ) : (
              <RecordViewSection title="Amounts" icon={<Percent className="size-4" />}>
                <RecordDetailRow label="Commission" value={displayValue(values.commission)} />
                <RecordDetailRow label="Net" value={formatRecordMoney(values.net)} />
              </RecordViewSection>
            )}

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

          {hasLinkedTransactions ? (
            <RecordViewSection title="Linked transactions" icon={<Layers3 className="size-4" />}>
              <div className="overflow-x-auto">
                <table className="w-full min-w-[32rem] border-collapse text-sm">
                  <thead>
                    <tr className="border-b text-left text-muted-foreground">
                      <th className="px-2 py-2 font-medium">Date</th>
                      <th className="px-2 py-2 font-medium">Ref. ID</th>
                      <th className="px-2 py-2 text-right font-medium">Quantity</th>
                      <th className="px-2 py-2 text-right font-medium">{priceLabel}</th>
                      <th className="px-2 py-2 text-right font-medium">Line total</th>
                    </tr>
                  </thead>
                  <tbody>
                    {linkedTransactions.map((row) => (
                      <tr key={row.dividentId} className="border-b last:border-0">
                        <td className="px-2 py-2 align-top">
                          <div>
                            {row.date
                              ? formatApiDate(row.date, "dd MMM yyyy", row.date) || row.date
                              : "—"}
                          </div>
                          {row.fTypeLabel ? (
                            <div className="text-xs text-muted-foreground">{row.fTypeLabel}</div>
                          ) : null}
                        </td>
                        <td className="px-2 py-2 align-top font-mono text-xs">
                          {displayValue(row.refId)}
                        </td>
                        <td className="px-2 py-2 text-right tabular-nums">
                          {formatLinkedNumber(row.quantity)}
                        </td>
                        <td className="px-2 py-2 text-right tabular-nums">
                          {formatLinkedNumber(row.amount)}
                        </td>
                        <td className="px-2 py-2 text-right tabular-nums">
                          {formatRecordMoney(row.lineTotal)}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                  <tfoot>
                    <tr className="border-t font-medium">
                      <td className="px-2 py-2" colSpan={2}>
                        Total
                      </td>
                      <td className="px-2 py-2 text-right tabular-nums">
                        {formatLinkedNumber(linkedQtyTotal)}
                      </td>
                      <td className="px-2 py-2" />
                      <td className="px-2 py-2 text-right tabular-nums">
                        {formatRecordMoney(linkedLineTotal)}
                      </td>
                    </tr>
                  </tfoot>
                </table>
              </div>
            </RecordViewSection>
          ) : null}
        </>
      ) : null}
    </RecordViewShell>
  );
}
