import type { Channel } from './shared';
import { Users, Zap } from 'lucide-react';
import { formatSats, formatTimestamp, truncateMiddle, PAYMENT_TONES } from './format';
import { Amount } from './Amount';
import { EmptyWallet, UnsupportedSection } from './EmptyWallet';
import { useSelectedWallet } from './useSelectedWallet';
import { useCapabilities, useChannels, usePayments, usePeers } from './useWalletData';

// The node's own view of itself: payments it has made, channels it holds, peers it is connected to.
//
// lndhub and nwc have no channels or peers of their own — they are accounts on someone else's node — so
// those blocks are absent from their capability set and never rendered. Nothing here shows a control that
// would come back 501.

export const LightningView = () => {
  const { walletId, isLoading } = useSelectedWallet();
  const { capabilities } = useCapabilities(walletId);
  const hasChannels = capabilities.includes('channels');
  const hasPeers = capabilities.includes('peers');
  const hasPayments = capabilities.includes('lightningSend');
  const anyLightning = hasChannels || hasPeers || hasPayments || capabilities.includes('lightningReceive');

  const { channels } = useChannels(walletId, hasChannels);
  const { peers } = usePeers(walletId, hasPeers);
  const { payments } = usePayments(walletId, hasPayments, 25);

  if (!walletId) return <EmptyWallet isLoading={isLoading} />;
  if (!anyLightning) return <UnsupportedSection what="lightning" />;

  return (
    <div className="h-full space-y-4 overflow-y-auto p-4">
      {hasChannels && (
        <Section title="Channels" count={channels.length}>
          {channels.length === 0 ? (
            <Blank>No channels open.</Blank>
          ) : (
            <ul className="divide-y divide-border">
              {channels.map((channel) => (
                <ChannelRow key={channel.channelId} channel={channel} />
              ))}
            </ul>
          )}
        </Section>
      )}

      {hasPeers && (
        <Section title="Peers" count={peers.length}>
          {peers.length === 0 ? (
            <Blank>Not connected to anyone.</Blank>
          ) : (
            <ul className="divide-y divide-border">
              {peers.map((peer) => (
                <li key={peer.pubkey} className="flex items-center gap-2 py-2 text-xs">
                  <Users className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                  <span className="min-w-0 flex-1 truncate">{peer.alias || truncateMiddle(peer.pubkey, 14, 8)}</span>
                  <span className="shrink-0 font-mono text-[10px] text-muted-foreground">{peer.address}</span>
                  <span className="shrink-0 text-[10px] text-muted-foreground">
                    {peer.inbound ? 'inbound' : 'outbound'}
                  </span>
                </li>
              ))}
            </ul>
          )}
        </Section>
      )}

      {hasPayments && (
        <Section title="Payments" count={payments.length}>
          {payments.length === 0 ? (
            <Blank>Nothing sent yet.</Blank>
          ) : (
            <ul className="divide-y divide-border">
              {payments.map((payment) => (
                <li key={payment.paymentHash} className="py-2">
                  <div className="flex items-center gap-2 text-xs">
                    <Zap className="h-3.5 w-3.5 shrink-0 text-amber-500" />
                    <span className="min-w-0 flex-1 truncate">
                      {payment.memo || truncateMiddle(payment.destination ?? payment.paymentHash, 14, 8)}
                    </span>
                    <span
                      className={`shrink-0 rounded px-1.5 py-px text-[10px] font-medium ${PAYMENT_TONES[payment.status]}`}
                    >
                      {payment.status}
                    </span>
                    {/* msat stays a string all the way to the DOM — see format.ts. */}
                    <Amount msat={payment.amountMsat} className="shrink-0 font-semibold" />
                  </div>
                  <div className="mt-0.5 pl-5 text-[11px] text-muted-foreground">
                    {formatTimestamp(payment.createdAt)} · fee <Amount msat={payment.feeMsat} />
                    {payment.failureReason && <span className="text-destructive"> · {payment.failureReason}</span>}
                  </div>
                </li>
              ))}
            </ul>
          )}
        </Section>
      )}
    </div>
  );
};

const ChannelRow = ({ channel }: { channel: Channel }) => {
  const capacity = channel.capacitySats || 1;
  const localPct = Math.max(0, Math.min(100, (channel.localBalanceSats / capacity) * 100));

  return (
    <li className="py-2.5">
      <div className="flex items-center gap-2 text-xs">
        <span
          className={`h-1.5 w-1.5 shrink-0 rounded-full ${channel.active ? 'bg-emerald-500' : 'bg-muted-foreground'}`}
          title={channel.active ? 'active' : channel.status}
        />
        <span className="min-w-0 flex-1 truncate">
          {channel.remoteAlias || truncateMiddle(channel.remotePubkey, 14, 8)}
        </span>
        {channel.private && <span className="shrink-0 text-[10px] text-muted-foreground">private</span>}
        <Amount sats={channel.capacitySats} className="shrink-0 text-[11px] text-muted-foreground" />
      </div>

      {/* Local/remote split — the number that decides whether you can send or only receive. */}
      <div className="mt-1.5 flex h-1.5 overflow-hidden rounded-full bg-muted">
        <div className="bg-primary" style={{ width: `${localPct}%` }} />
      </div>
      <div className="mt-1 flex justify-between text-[10px] tabular-nums text-muted-foreground">
        <span>out {formatSats(channel.localBalanceSats)}</span>
        <span>in {formatSats(channel.remoteBalanceSats)}</span>
      </div>
    </li>
  );
};

type SectionProps = { title: string; count: number; children: React.ReactNode };

const Section = ({ title, count, children }: SectionProps) => (
  <section className="rounded-xl border border-border p-4">
    <h3 className="mb-2 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">
      {title}
      {count > 0 && <span className="ml-1.5 font-normal">({count})</span>}
    </h3>
    {children}
  </section>
);

const Blank = ({ children }: { children: React.ReactNode }) => (
  <p className="text-xs text-muted-foreground">{children}</p>
);
