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

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

export type BankAccountItem = {
  id: string;
  name: string;
  balance?: string;
  institutionName?: string;
  institutionLogoUrl?: string;
};

export type BankAccountCategory =
  | "banking"
  | "home-loan"
  | "credit-card"
  | "personal-loan";

export type BankAccountsByCategory = Partial<
  Record<BankAccountCategory, BankAccountItem[]>
>;

export type BankingAccountsConnectApplicant = {
  name: string;
  email?: string;
};

export type BankingAccountsConnectProps = {
  applicant: BankingAccountsConnectApplicant;
  /** Connected accounts grouped by category. All accounts are flattened and shown in a single grid. */
  accountsByCategory?: BankAccountsByCategory;
  /** Called when the "Connect Your Bank +" tile is clicked. */
  onConnectBank?: () => void;
  onNext?: () => void;
  onPrev?: () => void;
  /** Hide the built-in Previous/Next navigation row — use when the parent wizard shell provides navigation. */
  hideNavigation?: boolean;
  className?: string;
};

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

/**
 * BankingAccountsConnect — shown on the Connections tab when the applicant
 * already has at least one bank account connected.
 *
 * Renders all connected accounts as horizontal card tiles plus a
 * "Connect Your Bank +" tile to add more. Layout mirrors the bank-selection
 * grid in ConnectBankStep.
 *
 * Figma: WealthX-Backoffice---Mobile-App — node 19308:53046 (Connection section)
 */
export function BankingAccountsConnect({
  accountsByCategory = {},
  onConnectBank,
  onNext,
  onPrev,
  hideNavigation = false,
  className,
}: BankingAccountsConnectProps) {
  // Flatten all category accounts into a single list for display
  const allAccounts = ([] as BankAccountItem[]).concat(
    ...Object.values(accountsByCategory),
  );

  return (
    <div className={cn("flex flex-col gap-6 font-sans", className)}>
      {/* Heading with left accent bar */}
      <div className="border-l-4 border-primary pl-3">
        <h2 className="text-h3 text-foreground">
          Connect Available Banking Information
        </h2>
        <p className="mt-1 text-body-small text-muted-foreground">
          This will help auto-populate your application form and remove the need
          to upload bank statements.
        </p>
      </div>

      {/* Connected accounts grid */}
      <div className="flex flex-col gap-3">
        <h3 className="text-label-large text-foreground">
          Your Connected Accounts
        </h3>

        {/* Tile grid — same border-collapse trick as ConnectBankStep. Capped at
            2 columns (1 on mobile): the wizard's content area is ~628px wide
            regardless of viewport, so 3 columns leave too little room for
            longer account names (e.g. "ANZ Home Loan ••4512") and truncate
            even on desktop. */}
        <div className="grid grid-cols-1 border-l border-t border-border sm:grid-cols-2">
          {allAccounts.map((account: BankAccountItem) => (
            <div
              key={account.id}
              className="flex h-[82px] items-center gap-3 border-b border-r border-border bg-background p-3"
            >
              {/* Institution logo or abbreviation */}
              {account.institutionLogoUrl ? (
                <img
                  src={account.institutionLogoUrl}
                  alt={account.institutionName ?? ""}
                  className="size-[50px] shrink-0 object-contain"
                />
              ) : (
                <div className="flex size-[50px] shrink-0 items-center justify-center bg-muted text-caption text-muted-foreground">
                  {account.institutionName?.[0] ?? "?"}
                </div>
              )}

              {/* Account name + balance */}
              <div className="flex min-w-0 flex-col">
                <span className="truncate text-body-small text-foreground">
                  {account.name}
                </span>
                {account.balance && (
                  <span className="text-label-small text-foreground">
                    {account.balance}
                  </span>
                )}
              </div>
            </div>
          ))}

          {/* "Connect Your Bank +" tile */}
          <button
            type="button"
            onClick={onConnectBank}
            className="flex h-[82px] 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>

      {/* Navigation — hidden when the parent wizard shell owns navigation */}
      {!hideNavigation && (
        <div className="flex items-center justify-between border-t border-border pt-4">
          <Button variant="outline" onClick={onPrev}>
            <ChevronLeft className="mr-1 size-4" />
            Previous
          </Button>
          <Button onClick={onNext}>
            Next
            <ChevronRight className="ml-1 size-4" />
          </Button>
        </div>
      )}
    </div>
  );
}
