import React from "react";
import { cn } from "@/lib/utils";
import { formatCurrency } from "@/lib/format-currency";
import { Button } from "./button";
import { Plus } from "lucide-react";

export type AccountCarouselType = "bankAccount" | "credit" | "propertyLoan";

export interface AccountCarouselItem {
  id: string;
  name: string;
  /** Institution name (e.g. "Commonwealth Bank") */
  institution: string;
  balance: number;
}

export interface AccountListCarouselProps {
  accounts: AccountCarouselItem[];
  type: AccountCarouselType;
  /** When provided, shows an "Add Account" button at the end (hidden for propertyLoan) */
  onAddAccount?: () => void;
  className?: string;
}

function AccountCard({
  item,
  isCombined,
}: {
  item: { name: string; institution?: string; balance: number };
  isCombined?: boolean;
}) {
  return (
    <div className="flex shrink-0 flex-col gap-1.5 border border-border p-3 w-36">
      <p className="text-xs text-muted-foreground truncate">
        {isCombined ? "All accounts" : item.institution}
      </p>
      <p className="text-sm font-medium text-foreground truncate">
        {item.name}
      </p>
      <p className="text-sm font-semibold tabular-nums text-foreground">
        {formatCurrency(item.balance)}
      </p>
    </div>
  );
}

export function AccountListCarousel({
  accounts,
  type,
  onAddAccount,
  className,
}: AccountListCarouselProps) {
  const combinedBalance = accounts.reduce((sum, a) => sum + a.balance, 0);
  const showCombined = type === "bankAccount" && accounts.length > 0;
  const showAddButton = type !== "propertyLoan" && onAddAccount;

  return (
    <div
      className={cn(
        "flex gap-2 overflow-x-auto pb-1 scrollbar-none",
        className,
      )}
    >
      {showCombined && (
        <AccountCard
          item={{ name: "Combined", balance: combinedBalance }}
          isCombined
        />
      )}

      {accounts.map((account) => (
        <AccountCard key={account.id} item={account} />
      ))}

      {showAddButton && (
        <Button
          variant="outline"
          onClick={onAddAccount}
          className="shrink-0 h-auto w-36 flex-col gap-1.5 border-dashed p-3 text-muted-foreground"
        >
          <Plus className="h-4 w-4" />
          <span className="text-xs">Add Account</span>
        </Button>
      )}
    </div>
  );
}
