import type { OnchainTx } from './shared';
import { ArrowDownLeft, ArrowUpRight, Loader2 } from 'lucide-react';
import { formatConfirmations, formatSats, formatTimestamp, truncateMiddle } from './format';
import { Amount } from './Amount';
import { EmptyWallet } from './EmptyWallet';
import { SyncBadge } from './SyncBadge';
import { useSelectedWallet } from './useSelectedWallet';
import { useTransactions } from './useWalletData';

// On-chain history. Works while locked — the transaction list comes from the account xpub, not the seed.

export const TransactionsView = () => {
  const { walletId, isLoading } = useSelectedWallet();
  const { transactions, sync, isLoading: txLoading } = useTransactions(walletId);

  if (!walletId) return <EmptyWallet isLoading={isLoading} />;

  if (txLoading && transactions.length === 0) {
    return (
      <div className="flex h-full items-center justify-center gap-2 text-sm text-muted-foreground">
        <Loader2 className="h-4 w-4 animate-spin" />
        Reading the chain…
      </div>
    );
  }

  if (transactions.length === 0) {
    // An empty list means "no transactions" only if we actually managed to look. When the chain has never
    // been read, the same screen would otherwise assert a fact nobody established.
    const neverRead = sync !== null && sync.syncedAt === null;
    return (
      <div className="flex h-full flex-col items-center justify-center gap-1 p-8 text-center">
        <p className="text-sm font-medium">{neverRead ? 'History unavailable' : 'Nothing here yet'}</p>
        <p className="text-xs text-muted-foreground">
          {neverRead
            ? (sync.lastError ?? 'The chain source could not be reached.')
            : 'Transactions appear as soon as they hit the mempool.'}
        </p>
      </div>
    );
  }

  return (
    <div className="flex h-full flex-col">
      <div className="flex shrink-0 items-center justify-end border-b border-border px-4 py-1.5">
        <SyncBadge sync={sync} />
      </div>
      <div className="flex-1 overflow-y-auto">
        <ul className="divide-y divide-border">
          {transactions.map((tx) => (
            <TransactionRow key={tx.txid} tx={tx} />
          ))}
        </ul>
      </div>
    </div>
  );
};

const TransactionRow = ({ tx }: { tx: OnchainTx }) => {
  const incoming = tx.amount >= 0;
  const pending = tx.confirmations <= 0;

  return (
    <li className="flex items-center gap-3 px-4 py-2.5">
      <span
        className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-full ${
          incoming ? 'bg-emerald-500/10 text-emerald-500' : 'bg-muted text-muted-foreground'
        }`}
      >
        {incoming ? <ArrowDownLeft className="h-3.5 w-3.5" /> : <ArrowUpRight className="h-3.5 w-3.5" />}
      </span>

      <div className="min-w-0 flex-1">
        <div className="truncate text-xs font-medium">
          {tx.label || truncateMiddle(tx.destAddresses[0] ?? tx.txid, 14, 10)}
        </div>
        <div className="mt-0.5 flex items-center gap-2 text-[11px] text-muted-foreground">
          <span>{formatTimestamp(tx.timestamp)}</span>
          <span className={pending ? 'text-amber-500' : ''}>{formatConfirmations(tx.confirmations)}</span>
          {tx.feeSats != null && tx.feeSats > 0 && <span>fee {formatSats(tx.feeSats)}</span>}
        </div>
      </div>

      <div className="shrink-0 text-right">
        <Amount sats={tx.amount} signed className="text-xs font-semibold" />
        <div className="mt-0.5 font-mono text-[10px] text-muted-foreground">{truncateMiddle(tx.txid, 8, 6)}</div>
      </div>
    </li>
  );
};
