import * as React from "react";
import {
  ChevronLeft,
  ChevronRight,
  CreditCard,
  KeyRound,
  ShieldCheck,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";

// ─── Types ────────────────────────────────────────────────────────────────────

export type ConnectBankApplicant = {
  name: string;
  email?: string;
  isMain?: boolean;
};

export type BankTile = {
  id: string;
  name: string;
  /** Optional logo URL. Falls back to abbreviated name. */
  logoUrl?: string;
};

/**
 * Default AU banks shown in the connect grid (matches Figma design).
 * logoUrl values are relative paths served from the Storybook public directory.
 * In production, override `banks` prop with CDN-hosted URLs.
 */
export const DEFAULT_BANKS: BankTile[] = [
  { id: "commonwealth", name: "CommBank", logoUrl: "/banks/commbank.png" },
  { id: "nab", name: "NAB", logoUrl: "/banks/nab.png" },
  { id: "anz", name: "ANZ", logoUrl: "/banks/anz.png" },
  {
    id: "bank-australia",
    name: "Bank Australia",
    logoUrl: "/banks/bank-australia.png",
  },
  {
    id: "regional-australia-bank",
    name: "Regional Australia Bank",
    logoUrl: "/banks/regional-australia-bank.png",
  },
];

export type SecurityItem = {
  text: string;
  icon?: React.ReactNode;
};

export const DEFAULT_SECURITY_ITEMS: SecurityItem[] = [
  {
    text: "Bank grade 256-bit SSL encryption",
    icon: <ShieldCheck className="size-5" />,
  },
  {
    text: "We never save your bank login credentials in the app",
    icon: <KeyRound className="size-5" />,
  },
  {
    text: "We cannot make transactions on your behalf",
    icon: <CreditCard className="size-5" />,
  },
];

export type ConnectBankStepProps = {
  applicant: ConnectBankApplicant;
  /** Whether the current user has been granted banking access for this applicant. */
  allowToAccessBanking?: boolean;
  /** Featured banks to show as individual tiles. Defaults to 5 AU banks. A
   *  "Connect Your Bank +" tile is always appended as the 6th cell. */
  banks?: BankTile[];
  /** Called when a specific bank tile OR the generic "Connect Your Bank +" is clicked. */
  onConnect?: (bank?: BankTile) => void;
  onManualAdd?: () => void;
  onSendRequest?: () => void;
  onPrev?: () => void;
  hideManualAdd?: boolean;
  hideNavigation?: boolean;
  hideCdrBanner?: boolean;
  /** Security/trust items shown below the CDR banner. Defaults to 3 standard AU Open Banking items. */
  securityItems?: SecurityItem[];
  /** URL for the Consumer Data Right logo. Falls back to an inline SVG placeholder. */
  cdrLogoUrl?: string;
  /** URL for the Australian Government crest. Falls back to an inline SVG placeholder. */
  govLogoUrl?: string;
  className?: string;
};

// ─── Component ────────────────────────────────────────────────────────────────

/**
 * ConnectBankStep — prompts the applicant to connect their bank accounts
 * via Open Banking (Basiq).
 *
 * States:
 * - `allowToAccessBanking=true` — shows CDR section + featured bank grid
 *   + "Connect Your Bank +" + "Or Add manually"
 * - `allowToAccessBanking=false` — shows "Send join invitation" CTA only
 *   (used for co-applicants who haven't yet granted access)
 *
 * Mirrors `ConnectBankStep` + `ConnectBankSection` + `BankConnectBanner`
 * from the frontend app.
 *
 * Figma: WealthX-Backoffice---Mobile-App — node 19308:52803
 */
export function ConnectBankStep({
  applicant,
  allowToAccessBanking = false,
  banks = DEFAULT_BANKS,
  onConnect,
  onManualAdd,
  onSendRequest,
  onPrev,
  hideManualAdd = false,
  hideNavigation = false,
  hideCdrBanner = false,
  securityItems = DEFAULT_SECURITY_ITEMS,
  cdrLogoUrl,
  govLogoUrl,
  className,
}: ConnectBankStepProps) {
  const name = applicant.name || "applicant";

  return (
    <div className={cn("flex flex-col gap-6 font-sans", className)}>
      {/* Heading — h1, dynamic applicant name */}
      <h2 className="text-h3 text-foreground">
        Connect {name}&apos;s Bank Accounts
      </h2>

      <p className="text-body-large text-foreground">
        Connect bank accounts &amp; speed up your application by 20 mins.
      </p>

      {/* CDR trust section */}
      {!hideCdrBanner && (
        <div className="flex flex-col gap-3">
          <div className="flex items-center gap-6">
            <CdrLogo logoUrl={cdrLogoUrl} />
            <AustralianGovLogo logoUrl={govLogoUrl} />
          </div>
          <p className="text-body-medium text-muted-foreground">
            We are powered by Open Banking, the safest and most secure way to
            share your information with trusted advisers. Learn more at{" "}
            <a
              href="https://www.cdr.gov.au/"
              target="_blank"
              rel="noopener noreferrer"
              className="text-primary hover:underline"
            >
              https://www.cdr.gov.au/
            </a>
          </p>

          {/* Security items */}
          {securityItems.length > 0 && (
            <div className="flex flex-col gap-2">
              {securityItems.map((item, i) => (
                <div
                  key={i}
                  className="flex items-center justify-between border border-primary bg-secondary/10 px-4 py-3"
                >
                  <span className="text-body-medium text-foreground">
                    {item.text}
                  </span>
                  {item.icon && (
                    <span className="ml-3 shrink-0 text-primary">
                      {item.icon}
                    </span>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {allowToAccessBanking ? (
        <>
          {/* Bank connect section */}
          <div className="flex flex-col gap-3">
            <h3 className="text-h5 text-foreground">Connect Bank Account</h3>

            {/* Bank grid: featured banks + generic "Connect Your Bank +" */}
            <div className="grid grid-cols-3 border-l border-t border-border">
              {banks.map((bank) => (
                <button
                  key={bank.id}
                  type="button"
                  onClick={() => onConnect?.(bank)}
                  className="flex h-[71px] items-center justify-center border-b border-r border-border bg-background p-3 transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
                >
                  {bank.logoUrl ? (
                    <img
                      src={bank.logoUrl}
                      alt={bank.name}
                      className="max-h-10 w-auto object-contain"
                    />
                  ) : (
                    // Text fallback when no logo — 14px bold per Figma tile spec
                    <span className="text-button text-foreground">
                      {bank.name}
                    </span>
                  )}
                </button>
              ))}

              {/* Generic "Connect Your Bank +" tile — 14px bold per Figma */}
              <button
                type="button"
                onClick={() => onConnect?.()}
                className="flex h-[71px] items-center justify-center gap-1.5 border-b border-r border-border bg-background p-3 transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
              >
                <span className="text-button text-foreground">
                  Connect Your Bank +
                </span>
              </button>
            </div>
          </div>

          {/* Divider */}
          <hr className="border-border" />

          {!hideManualAdd && (
            <div className="flex flex-col gap-3">
              <h3 className="text-h5 text-foreground">Or Add manually</h3>
              <Button
                variant="outline"
                className="w-fit gap-1.5"
                onClick={onManualAdd}
              >
                Start form
                <ChevronRight className="size-4" />
              </Button>
            </div>
          )}
        </>
      ) : (
        /* Co-applicant — no access yet */
        <Button className="w-full" onClick={onSendRequest}>
          Send join invitation to {name}
        </Button>
      )}

      {/* Navigation */}
      {!hideNavigation && (
        <div className="pt-2">
          <Button variant="outline" onClick={onPrev}>
            <ChevronLeft className="mr-1 size-4" />
            Previous
          </Button>
        </div>
      )}
    </div>
  );
}

// ─── CDR / Gov logos ──────────────────────────────────────────────────────────

/** Consumer Data Right logo — uses real image when `logoUrl` is provided, falls back to SVG placeholder */
function CdrLogo({ logoUrl }: { logoUrl?: string }) {
  if (logoUrl) {
    return (
      <img
        src={logoUrl}
        alt="Consumer Data Right"
        className="h-[76px] w-auto object-contain"
      />
    );
  }
  return (
    <div className="flex items-center gap-2">
      <svg
        width="48"
        height="48"
        viewBox="0 0 48 48"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
        aria-label="Consumer Data Right"
      >
        <circle cx="24" cy="24" r="22" stroke="#0057A8" strokeWidth="2" />
        <circle cx="24" cy="24" r="14" stroke="#0057A8" strokeWidth="2" />
        <circle cx="24" cy="24" r="6" fill="#0057A8" />
        <circle cx="24" cy="6" r="3" fill="#0057A8" />
        <circle cx="24" cy="42" r="3" fill="#0057A8" />
        <circle cx="6" cy="24" r="3" fill="#0057A8" />
        <circle cx="42" cy="24" r="3" fill="#0057A8" />
      </svg>
      <div className="flex flex-col">
        <span className="text-label-small text-[#0057A8]">Consumer</span>
        <span className="text-label-small text-[#0057A8]">Data Right</span>
      </div>
    </div>
  );
}

/** Australian Government crest — uses real image when `logoUrl` is provided, falls back to SVG placeholder */
function AustralianGovLogo({ logoUrl }: { logoUrl?: string }) {
  if (logoUrl) {
    return (
      <img
        src={logoUrl}
        alt="Australian Government"
        className="h-[70px] w-auto object-contain"
      />
    );
  }
  return (
    <div className="flex flex-col items-center gap-0.5">
      {/* Simplified coat of arms silhouette */}
      <svg
        width="40"
        height="36"
        viewBox="0 0 40 36"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
        aria-label="Australian Government"
      >
        <ellipse
          cx="20"
          cy="22"
          rx="14"
          ry="10"
          stroke="#333"
          strokeWidth="1.5"
        />
        <circle cx="20" cy="10" r="6" stroke="#333" strokeWidth="1.5" />
        <path
          d="M14 18 Q20 8 26 18"
          stroke="#333"
          strokeWidth="1.5"
          fill="none"
        />
        <line x1="10" y1="28" x2="30" y2="28" stroke="#333" strokeWidth="1.5" />
      </svg>
      <span className="text-label-small text-foreground">
        Australian Government
      </span>
    </div>
  );
}
