import * as React from "react";
import { CircleAlert, CircleCheck, FileClock } from "lucide-react";
import { cn } from "@/lib/utils";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";

/**
 * StatementVerifyResult - WealthX DS (L4 Template)
 *
 * The public page a statement recipient lands on after scanning the QR code
 * printed on a generated statement, or after entering its verification
 * reference at the verify URL.
 *
 * The page confirms provenance only: who issued the document, for which
 * account and period, and that the copy in hand matches the issued original.
 * It deliberately shows no balances, no transactions and no full account
 * number, because the reader is whoever holds the PDF rather than an
 * authenticated user.
 *
 * Layer: L4 Template
 */

export type StatementVerifyStatus = "verified" | "not-found" | "superseded";

export interface StatementVerifyDocument {
  /** e.g. "Account statement". */
  documentType?: string;
  institutionName?: string;
  institutionLogo?: string;
  /** e.g. "Everyday Access". */
  productName?: string;
  /** Masked identifier, e.g. "BSB 062-000, account ending 5678". */
  accountMasked?: string;
  /** Pre-formatted range, e.g. "01 May 2026 - 31 Jul 2026". */
  statementPeriod?: string;
  /** Pre-formatted date and time the statement was generated. */
  generatedOn?: string;
  /** Initialised holder name, e.g. "J. Whitfield". */
  issuedTo?: string;
  issuedBy?: string;
  pageCount?: number;
  /** Truncated content hash the recipient can match against their copy. */
  fingerprint?: string;
}

export interface StatementVerifyResultProps {
  status: StatementVerifyStatus;
  reference?: string;
  document?: StatementVerifyDocument;
  /** Brand lockup rendered above the card. */
  logoNode?: React.ReactNode;
  /** Reference of the document that replaced this one. */
  supersededByReference?: string;
  onCheckAnother?: () => void;
  className?: string;
}

const NOT_RECORDED = "Not recorded";

const STATUS_PRESENTATION: Record<
  StatementVerifyStatus,
  {
    icon: React.ComponentType<{ className?: string }>;
    title: string;
    badge: string;
    badgeVariant: "success" | "destructive" | "warning";
    tone: string;
  }
> = {
  verified: {
    icon: CircleCheck,
    title: "This statement is genuine",
    badge: "Verified",
    badgeVariant: "success",
    tone: "text-success-text",
  },
  "not-found": {
    icon: CircleAlert,
    title: "We do not recognise this reference",
    badge: "Not found",
    badgeVariant: "destructive",
    tone: "text-destructive-text",
  },
  superseded: {
    icon: FileClock,
    title: "This statement has been replaced",
    badge: "Superseded",
    badgeVariant: "warning",
    tone: "text-warning-text",
  },
};

function DetailRow({
  label,
  value,
  mono = false,
}: {
  label: string;
  value?: React.ReactNode;
  mono?: boolean;
}) {
  const isEmpty = value === undefined || value === null || value === "";

  return (
    <div className="flex flex-col gap-1 py-3 md:flex-row md:items-baseline md:gap-6">
      <span className="text-label-small text-muted-foreground md:w-52 md:shrink-0">
        {label}
      </span>
      <span
        className={cn(
          "min-w-0 break-words",
          mono ? "text-code" : "text-body-small",
          isEmpty ? "text-muted-foreground" : "text-foreground",
        )}
      >
        {isEmpty ? NOT_RECORDED : value}
      </span>
    </div>
  );
}

export function StatementVerifyResult({
  status,
  reference,
  document,
  logoNode,
  supersededByReference,
  onCheckAnother,
  className,
}: StatementVerifyResultProps) {
  const presentation = STATUS_PRESENTATION[status];
  const StatusIcon = presentation.icon;

  return (
    <div
      data-slot="statement-verify-result"
      className={cn(
        "mx-auto flex w-full max-w-[720px] flex-col gap-6 px-4 py-10",
        className,
      )}
    >
      {logoNode}

      <Card>
        <CardContent className="flex flex-col gap-6">
          <div className="flex flex-col gap-3">
            <div className="flex items-start gap-3">
              <StatusIcon className={cn("mt-1 size-6 shrink-0", presentation.tone)} />
              <div className="flex min-w-0 flex-col gap-2">
                <h1 className="text-h4 text-foreground">{presentation.title}</h1>
                <Badge variant={presentation.badgeVariant} className="w-fit">
                  {presentation.badge}
                </Badge>
              </div>
            </div>

            {status === "verified" && (
              <p className="text-body-small text-muted-foreground">
                WealthX issued this document from Consumer Data Right banking
                data. The details below are what we recorded when it was
                generated. Check them against the copy you are holding.
              </p>
            )}
            {status === "not-found" && (
              <p className="text-body-small text-muted-foreground">
                No document with this reference has been issued by WealthX.
                Check for a typing error, then contact the person who sent you
                the document. Treat it as unverified until it checks out here.
              </p>
            )}
            {status === "superseded" && (
              <p className="text-body-small text-muted-foreground">
                This document was genuine when issued, but a corrected version
                has since replaced it. Ask the sender for the current statement
                before relying on the figures.
              </p>
            )}
          </div>

          <div className="flex flex-col divide-y divide-border border-t border-b border-border">
            <DetailRow label="Verification reference" value={reference} mono />
            {status === "superseded" && (
              <DetailRow
                label="Replaced by"
                value={supersededByReference}
                mono
              />
            )}
            {status !== "not-found" && (
              <>
                <DetailRow
                  label="Document"
                  value={document?.documentType ?? "Account statement"}
                />
                <DetailRow
                  label="Financial institution"
                  value={
                    document?.institutionLogo ? (
                      <span className="flex items-center gap-2">
                        <img
                          src={document.institutionLogo}
                          alt=""
                          className="h-5 w-auto max-w-[96px] object-contain object-left"
                        />
                        {document.institutionName}
                      </span>
                    ) : (
                      document?.institutionName
                    )
                  }
                />
                <DetailRow label="Product" value={document?.productName} />
                <DetailRow label="Account" value={document?.accountMasked} />
                <DetailRow
                  label="Statement period"
                  value={document?.statementPeriod}
                />
                <DetailRow label="Issued to" value={document?.issuedTo} />
                <DetailRow label="Issued by" value={document?.issuedBy} />
                <DetailRow label="Generated on" value={document?.generatedOn} />
                <DetailRow
                  label="Pages"
                  value={document?.pageCount?.toString()}
                />
                <DetailRow
                  label="Document fingerprint"
                  value={document?.fingerprint}
                  mono
                />
              </>
            )}
          </div>

          <p className="text-caption text-muted-foreground">
            This page confirms who issued the document and that it has not been
            altered. It does not show balances, transactions or full account
            numbers. Only the account holder can share those.
          </p>

          {onCheckAnother && (
            <Button
              variant="outline"
              onClick={onCheckAnother}
              className="w-fit"
            >
              Check another reference
            </Button>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
