import type { LucideIcon } from 'lucide-react';
import type { WalletSummary } from './shared';
import { useState } from 'react';
import { Link, NavLink } from 'react-router';
import { ArrowDownLeft, ArrowUpRight, Bitcoin, Coins, Gauge, Plus, Receipt, Settings, Star, Zap } from 'lucide-react';
import {
  KIND_LABELS,
  NETWORK_TONES,
  WALLET_SECTIONS,
  sectionAvailable,
  walletSectionPath,
  type WalletSectionId,
} from './shared';
import { Amount, UnitToggle } from './Amount';
import { LockBadge } from './LockBadge';
import { useWalletSection } from './useWalletSection';
import { useSelectedWallet } from './useSelectedWallet';
import { useBalances, useCapabilities, useWalletConfig, useWalletLifecycle } from './useWalletData';
import { CreateWalletDialog } from './dialogs/CreateWalletDialog';

// Left panel of /wallet: the balance, the wallets, the sections, the lock state.
//
// Wallet rows are real links carrying `?wallet=<id>` — cmd-click, back button and reload all work, and the
// id is in the DOM rather than an onClick closure (docs/navigation-audit.md). "Make active" is a sibling
// button, not nested inside the anchor, because it mutates rather than navigates.
//
// Sections are filtered by the backend's declared capabilities: an on-chain wallet has no Lightning tab at
// all, an lndhub account has no coin control. Better a shorter nav than a control that answers 501.

const ICONS: Record<WalletSectionId, LucideIcon> = {
  overview: Gauge,
  receive: ArrowDownLeft,
  send: ArrowUpRight,
  transactions: Receipt,
  coins: Coins,
  lightning: Zap,
  settings: Settings,
};

const ROW = 'group relative flex items-center gap-3 rounded-lg px-3 py-2 text-left text-sm transition-colors';

export const WalletNav = () => {
  const section = useWalletSection();
  const { config } = useWalletConfig();
  const { wallet, wallets, walletId, isPinned, isLoading } = useSelectedWallet();
  const { capabilities } = useCapabilities(walletId);
  const { balances } = useBalances(walletId);
  const [createOpen, setCreateOpen] = useState(false);

  // Preserve an explicitly pinned wallet across section changes; leave a bare URL bare so it keeps
  // meaning "whichever wallet is active".
  const linkWalletId = isPinned ? walletId : null;
  const total = balances ? balances.onchainConfirmed + (balances.lightningBalance ?? 0) : null;
  const network = wallet?.network ?? config?.network ?? null;

  return (
    <div className="flex h-full flex-col overflow-y-auto bg-muted/30">
      <div className="flex items-center gap-3 px-4 py-4">
        <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-orange-500/15 text-orange-500 ring-1 ring-black/5">
          <Bitcoin className="h-5 w-5" />
        </div>
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-1.5">
            <span className="truncate text-sm font-semibold leading-tight">Wallet</span>
            {network && network !== 'bitcoin' && (
              <span className={`rounded px-1 py-px text-[9px] font-semibold uppercase ${NETWORK_TONES[network] ?? ''}`}>
                {network}
              </span>
            )}
          </div>
          <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
            <Amount sats={total} />
            <UnitToggle />
          </div>
        </div>
      </div>

      <div className="flex items-center justify-between px-5 pb-1">
        <span className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">Wallets</span>
        <button
          type="button"
          onClick={() => setCreateOpen(true)}
          className="flex items-center gap-0.5 text-[10px] font-medium text-primary hover:underline"
        >
          <Plus className="h-3 w-3" />
          add
        </button>
      </div>

      <div className="flex flex-col gap-0.5 px-2 pb-3">
        {isLoading && wallets.length === 0 && (
          <div className="px-3 py-2 text-xs text-muted-foreground">Loading wallets…</div>
        )}
        {!isLoading && wallets.length === 0 && (
          <div className="px-3 py-2 text-xs text-muted-foreground">
            No wallets yet. Add one to get started — a self-custodial seed, or a connection to your node.
          </div>
        )}
        {wallets.map((w) => (
          <WalletRow key={w.id} wallet={w} section={section} selected={w.id === walletId} />
        ))}
      </div>

      <nav className="flex flex-col gap-0.5 border-t border-border px-2 py-3">
        {WALLET_SECTIONS.filter(({ id }) => sectionAvailable(id, capabilities)).map(({ id, label }) => {
          const Icon = ICONS[id];
          return (
            <NavLink
              key={id}
              to={walletSectionPath(id, linkWalletId)}
              className={({ isActive }) =>
                `${ROW} ${
                  isActive
                    ? 'bg-primary/10 font-medium text-primary'
                    : 'text-muted-foreground hover:bg-muted hover:text-foreground'
                }`
              }
            >
              {({ isActive }) => (
                <>
                  {isActive && (
                    <span className="absolute left-0 top-1/2 h-5 w-1 -translate-y-1/2 rounded-r-full bg-primary" />
                  )}
                  <Icon
                    className={`h-4 w-4 shrink-0 ${isActive ? 'text-primary' : 'text-muted-foreground group-hover:text-foreground'}`}
                  />
                  <span className="flex-1">{label}</span>
                </>
              )}
            </NavLink>
          );
        })}
      </nav>

      <div className="mt-auto flex items-center justify-between gap-2 px-4 py-3">
        <LockBadge walletId={walletId} walletName={wallet?.name ?? 'this wallet'} />
        {config && <span className="truncate text-[10px] text-muted-foreground">{config.network}</span>}
      </div>

      {createOpen && <CreateWalletDialog open={createOpen} onOpenChange={setCreateOpen} section={section} />}
    </div>
  );
};

type WalletRowProps = { wallet: WalletSummary; section: WalletSectionId; selected: boolean };

const WalletRow = ({ wallet, section, selected }: WalletRowProps) => {
  const { activate } = useWalletLifecycle();

  return (
    <div
      className={`group flex items-center gap-1 rounded-lg pr-1.5 transition-colors ${
        selected ? 'bg-muted' : 'hover:bg-muted/60'
      }`}
    >
      <Link to={walletSectionPath(section, wallet.id)} className="flex min-w-0 flex-1 flex-col px-3 py-1.5">
        <span className={`truncate text-xs ${selected ? 'font-medium text-foreground' : 'text-muted-foreground'}`}>
          {wallet.name}
        </span>
        <span className="truncate text-[10px] text-muted-foreground">{KIND_LABELS[wallet.kind]}</span>
      </Link>
      {/* Sibling of the anchor, never nested inside it — this mutates, it does not navigate. */}
      {wallet.isActive ? (
        <Star className="h-3 w-3 shrink-0 fill-amber-400 text-amber-400" aria-label="Active wallet" />
      ) : (
        <button
          type="button"
          onClick={() => activate.mutate(wallet.id)}
          disabled={activate.isPending}
          title="Make this the active wallet"
          className="shrink-0 text-muted-foreground opacity-0 transition-opacity hover:text-amber-400 group-hover:opacity-100 focus:opacity-100"
        >
          <Star className="h-3 w-3" />
        </button>
      )}
    </div>
  );
};
